Friday, 10 January 2014

Upload Multiple Images/Photos to Server Using MulipartFormatData via AFNetworking

Below is the code snippet which would help in uploading multiple Images along with Text to Server:


-(void)uploadMultipleImagesWithTextMessageUsingAFNetworkingMultipartFormat:(id)sender {
    // Upload multiple images to server using multipartformatdata (AFNetworking)
   
    NSString *stringMessage = @"I am uploading multiple images to server";  
   
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: [NSURL URLWithString:BASEURL]]; // replace BASEURL
    client.parameterEncoding = AFJSONParameterEncoding;

    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"/PostMultImagesWithTextAPI" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
       
        [formData appendPartWithFormData:[[[NSUserDefaults standardUserDefaults] objectForKey:KServerAccessToken] dataUsingEncoding:NSUTF8StringEncoding] name:@"AccessToken"];
       
        [formData appendPartWithFormData:[stringMessage dataUsingEncoding:NSUTF8StringEncoding] name:@"PostText"];
       
        // arrayChosenImages is NSArray of UIImage to be uploaded
        for (int i=0; i<[arrayChosenImages count]; i++) {
            [formData appendPartWithFileData:UIImageJPEGRepresentation([arrayChosenImages objectAtIndex:i], 0.5)
                                        name:[NSString stringWithFormat:@"image%d",i]
                                    fileName:[NSString stringWithFormat:@"image%d.jpg",i]
                                    mimeType:@"image/jpeg"];
        }
    }];
   
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        float uploadPercentge = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;
        float uploadActualPercentage = uploadPercentge * 100;
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
        NSLog(@"Multipartdata upload in progress: %@",[NSString stringWithFormat:@"%.2f %%",uploadActualPercentage]);
        if (uploadActualPercentage >= 100) {
            NSLog(@"Waitting for response ...");
        }
        progressBar.progress = uploadPercentge; //  progressBar is UIProgressView to show upload progress
    }];
    [client enqueueHTTPRequestOperation:operation];
   
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *dataResponseJSON = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dictResponseJSON = [NSJSONSerialization JSONObjectWithData:dataResponseJSON options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"PostMultImagesWithTextAPI API Response: %@", dictResponseJSON);      
    }
     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"PostMultImagesWithTextAPI API failed with error: %@", operation.responseString);
     }];
    [operation start];
}

Hope it helps you...

4 comments:

  1. Hello. Thanks for this post. Can you explain me the difference between send all the images in a single request and make a request for each image? Thanks

    ReplyDelete
  2. Anonymous7 November 2014 at 16:01

    Hello. Thanks for this post. Can you explain me the difference between send all the images in a single request and make a request for each image? Thanks

    ReplyDelete
    Replies
    1. Sending multiple images in a single shot will take less time to get uploaded and sending each image at a time will need more time to get uploaded, as it will require to make connection/disconnection to server for each request.

      Delete
  3. how to show progress accordingly image upload (multiple image)

    ReplyDelete