Shay
Shay

Reputation: 2605

How to send multiple files with post request? (objective-c, iOS)

I want to sent post request, but i need to send multiple files, how to do this?

tnx

Upvotes: 1

Views: 1805

Answers (2)

kathayatnk
kathayatnk

Reputation: 1015

You have to create boundaries for different images to be uploaded. Let me explain step by step. 1. Convert your images to NSData and add them to dictionary.

    UIImage *image1 = [UIImage imageNamed:@"imageName"];        
    UIImage *image2 = [UIImage imageNamed:@"imageName"];       
    UIImage *image3 = [UIImage imageNamed:@"imageName"];

    NSMutableDictionary *imageDataDictionary = [[NSMutableDictionary alloc] init];
    [imageDataDictionary setObject:UIImagePNGRepresentation(image1) forKey:@"image"];
    [imageDataDictionary setObject:UIImagePNGRepresentation(image2) forKey:@"image"];
    [imageDataDictionary setObject:UIImagePNGRepresentation(image3) forKey:@"image"];
  1. When you have created the above dictionary its time to create body part for the request.

    NSMUtableData *finalPostData = [[NSMutableData alloc] init];
    NSString *boundary = @"0xKhTmLbOuNdArY";
    NSString *endBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary];
    [finalPostData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
    contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    
    for(NSString *key in imageDataDictionary)
    {
       imageData = [imageDataDictionary objectForKey:key];
       [finalPostData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
       [finalPostData appendData:[@"Content-Disposition: form-data; name=\"upload\"; filename=\"image.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
       [finalPostData appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
       [finalPostData appendData:[NSData dataWithData:imageData]];
       [finalPostData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
  2. When all the images are added. We have to end with final boundary.

    [finalPostData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
  3. Now our data is ready. We just have to append this to the body of the request.

Upvotes: 3

warrenm
warrenm

Reputation: 31782

Use one of the many resources on how to configure an NSMutableURLRequest for POSTing data. The Content-Type header should be "multipart/form-data", and each file will be concatenated in turn with an appropriate part header. RFC2388 is the relevant standard.

Upvotes: 2

Related Questions