Skip to content

Instantly share code, notes, and snippets.

@robin
Created December 30, 2008 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robin/41659 to your computer and use it in GitHub Desktop.
Save robin/41659 to your computer and use it in GitHub Desktop.
cocoa http upload
NSString *filename = @"myfile.png";
NSString *boundary = @"----BOUNDARY_IS_I";
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@SERVER_POSTIMAGE_PATH_STR, [[UIDevice currentDevice] uniqueIdentifier] ]];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[req setValue:contentType forHTTPHeaderField:@"Content-type"];
NSData *imageData = UIImagePNGRepresentation(anImage);
// adding the body
NSMutableData *postBody = [NSMutableData data];
// first parameter an image
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"upload\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:imageData];
// second parameter information
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"some_other_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"some_other_value" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r \n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:postBody];
NSURLResponse* response;
NSError* error;
NSData* result = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
NSString * rsltStr = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment