Created
January 17, 2014 01:49
-
-
Save mombrea/8467128 to your computer and use it in GitHub Desktop.
example of a multi-part form post in objective-c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"REST URL PATH"]]; | |
NSData *imageData = UIImageJPEGRepresentation(image, 1.0); | |
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; | |
[request setHTTPShouldHandleCookies:NO]; | |
[request setTimeoutInterval:60]; | |
[request setHTTPMethod:@"POST"]; | |
NSString *boundary = @"unique-consistent-string"; | |
// set Content-Type in HTTP header | |
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; | |
[request setValue:contentType forHTTPHeaderField: @"Content-Type"]; | |
// post body | |
NSMutableData *body = [NSMutableData data]; | |
// add params (all params are strings) | |
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@\r\n\r\n", @"imageCaption"] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[body appendData:[[NSString stringWithFormat:@"%@\r\n", @"Some Caption"] dataUsingEncoding:NSUTF8StringEncoding]]; | |
// add image data | |
if (imageData) { | |
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=imageName.jpg\r\n", @"imageFormKey"] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; | |
[body appendData:imageData]; | |
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; | |
} | |
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; | |
// setting the body of the post to the reqeust | |
[request setHTTPBody:body]; | |
// set the content-length | |
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; | |
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; | |
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { | |
if(data.length > 0) | |
{ | |
//success | |
} | |
}]; |
Thanks man! You saved me...
Thank you! You saved my day
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if you want to post a video using
multipart/form-data
?