Created
January 20, 2012 19:49
-
-
Save greenisus/1649217 to your computer and use it in GitHub Desktop.
multipart POST
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
+ (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