I want to sent post request, but i need to send multiple files, how to do this?
tnx
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.
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"];
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]];
}
When all the images are added. We have to end with final boundary.
[finalPostData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
Now our data is ready. We just have to append this to the body of the request.