Skip to content

Instantly share code, notes, and snippets.

@greenisus
Created January 20, 2012 19:49
Show Gist options
  • Save greenisus/1649217 to your computer and use it in GitHub Desktop.
Save greenisus/1649217 to your computer and use it in GitHub Desktop.
multipart POST
+ (void)multipartPost:(NSString *)path postParams:(NSDictionary *)postParams success:(void (^)(id object))successHandler
failure:(void (^)(NSHTTPURLResponse*, NSData*, NSError*))failureHandler NS_AVAILABLE(10_7, 5_0) {
NSString *boundary = @"----------------------------ToOdOiPhOnEaPp";
NSMutableURLRequest *request = [self postRequest:path];
NSString *contentType = $S(@"multipart/form-data, boundary=%@", boundary);
[request setValue:contentType forHTTPHeaderField:@"Content-type"];
NSMutableData *postBody = [[NSMutableData alloc] init];
for (NSString *key in postParams) {
[postBody appendData:[$S(@"\r\n--%@\r\n", boundary) dataUsingEncoding:NSUTF8StringEncoding]];
id value = [postParams objectForKey:key];
if ([value isKindOfClass:[NSData class]]) {
[postBody appendData:[$S(@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", key) dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:value];
} else {
[postBody appendData:[$S(@"--%@\r\n", boundary) dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[$S(@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key) dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[postBody appendData:[$S(@"\r\n--%@--\r\n", boundary) dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
[self sendAPIRequest:request success:successHandler failure:failureHandler];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment