Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

objective c - Uploading Multiple Images from iOS Camera to API

What my project does is takes pictures with a custom camera for an item and adds them to an NSMutableArray. Then, I grab those images and submit them to my API. I have tried almost every solution that I have found on StackOverflow and none have worked for me. I've used Multipart Request using AFNetworking and even with just NSURLRequests.

Currently, the item gets submitted but the images don't. Not sure if it is my API or the way I submit them.

Here is my .m file:

NSString *urlString = [NSString stringWithFormat:@"xxxxxxxxxxxxxxxx", xxxx]; // hidden for stackoverflow

NSLog(@"IMAGES URL: %@", urlString);

NSURL *url = [NSURL URLWithString:urlString];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:240];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"XXX--";

NSString *contentTypeValue = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentTypeValue forHTTPHeaderField:@"Content-type"];

NSMutableData *dataForm = [NSMutableData alloc];

[dataForm appendData:[[NSString stringWithFormat:@"
--%@
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="param1";

%@", @"10001"] dataUsingEncoding:NSUTF8StringEncoding]];

if ([globals.imagesArray count] != 0) {
    NSLog(@"PICTURES FROM CAMERA");
    
    imagesArray = globals.imagesArray;
    
    for (int i = 0;i < [imagesArray count];i++) {
        NSLog(@"Inside for loop: %d", i);
        
        UIImage *image = imagesArray[i];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.9);
        
        [dataForm appendData:[[NSString stringWithFormat:@"
--%@
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [dataForm appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="fileToUpload[]"; filename="%@%d.jpg"
", @"pic", i] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [dataForm appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg

"] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [dataForm appendData:[NSData dataWithData:imageData]];
        
        NSLog(@"TEST TEST %d", i);
        NSLog(@"IMAGES %@", imagesArray[i]);
    }
    
    NSURLSession *urlSession = [NSURLSession sharedSession];
    [dataForm appendData:[[NSString stringWithFormat:@"
--%@--
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLSessionUploadTask *uploadTask = [urlSession uploadTaskWithRequest:request fromData:dataForm completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (dataForm > 0) {
            NSLog(@"Successfully Uploaded Images!");
            
            dispatch_sync(dispatch_get_main_queue(), ^(void) {
                postItemViewController *home = [self.storyboard instantiateViewControllerWithIdentifier:@"tabBarController"];
                [self.navigationController pushViewController:home animated:YES];
                [self dismissViewControllerAnimated:YES completion:nil];
            });
        }
    }];
    
    [uploadTask resume];
    
} else {
    NSLog(@"PICTURES FROM GALLERY");

Here is my API that uploads the item and the images to the database:

// create directory if it doesn't exist
$target_dir = "../uploads/$year/$month/$day";
if (!is_dir("$target_dir")) {
    mkdir("$target_dir", 0755, true);
}

for ($i = 0; $i < $file_count; $i++) {
    $file_name[] = $_FILES['fileToUpload']['name'][$i];
    $temp_file_name[] = $_FILES['fileToUpload']['tmp_name'][$i];

    // echo $_FILES['fileToUpload']['name'][$i];
    // echo $_FILES['fileToUpload']['tmp_name'][$i];

    $path = $_FILES['fileToUpload']['name'][$i]; // Image
    $ext = pathinfo($path, PATHINFO_EXTENSION);
    $target_file = $target_dir . "/$lastID-$year-$month-$day-$hourminsec-$i.$ext";

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$i], $target_file)) {
        $file = "$year/$month/$day/$lastID-$year-$month-$day-$hourminsec-$i.$ext";
            $image_url = "$file";

        //successful upload, let's add path to image table.
        $query = "INSERT INTO `images` (`image_url`, item_id) VALUES ('$image_url', $lastID) ";
        $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
        echo $query;
    }
}

echo "SUCCESS";

SOLVED

If your images are not submitting via Camera, a possible issue could be the format of the image. I simply converted the image to JPG.

[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef  _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
    if (imageDataSampleBuffer != NULL) {
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:imageData];
       
        NSData *jpgImageData = UIImageJPEGRepresentation(image, 0.7);
        UIImage *jpgimage = [UIImage imageWithData:jpgImageData];
     }
}];

question from:https://stackoverflow.com/questions/65906987/uploading-multiple-images-from-ios-camera-to-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...