Created
June 27, 2013 14:38
-
-
Save cgreening/5876948 to your computer and use it in GitHub Desktop.
Create a multipart for request for posting
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
Use like this: | |
NSData* fileData = UIImageJPEGRepresentation(profileImage, 0.8f); | |
NSMutableURLRequest *request = [self.httpClient requestWithMethod:@"POST" path:@"api/users/updateSettings" parameters:params]; | |
[self setupMultipartRequest:request withParams:params data:fileData dataName:@"profileImage"]; | |
-(void) setupMultipartRequest:(NSMutableURLRequest *) request withParams:(NSDictionary *) params data:(NSData *) data dataName:(NSString *) dataName { | |
//Add the header info | |
NSString *stringBoundary = @"0xKhTmLbOuNdArY"; | |
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary]; | |
[request addValue:contentType forHTTPHeaderField: @"Content-Type"]; | |
//create the body | |
NSMutableData *postBody = [NSMutableData data]; | |
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; | |
//add key values from the NSDictionary object | |
for (NSString *key in params.allKeys) { | |
NSString *param = [params objectForKey:key]; | |
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:[[NSString stringWithFormat:@"%@",param] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; | |
} | |
//add data field and file data | |
// Content-Disposition: form-data; name="imageData"; filename="image.jpg" | |
// Content-Type: image/jpeg | |
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", dataName] dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; | |
[postBody appendData:[NSData dataWithData:data]]; | |
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; | |
//add the body to the post | |
[request setHTTPBody:postBody]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment