Multipart Form image upload in Cocoa or CFNetwork?
Multipart Form image upload in Cocoa or CFNetwork?
- Subject: Multipart Form image upload in Cocoa or CFNetwork?
- From: Todd Ditchendorf <email@hidden>
- Date: Wed, 5 Dec 2007 14:28:36 -0800
I'm looking for advice for writing native code in cocoa (NSURLConnection) or CFNetwork to do an HTTP Post with of type multipart-form to post an image to a web server as you would with a web form and <input type="file">
The server side is fully implemented and works using a webform, so now all i have to do is write a native client in cocoa or carbon.
Is it possible to do multipart-form posts using NSURLConnection or CFNetwork?
I've tried using NSURLConnection to more-or-less create the entire post body by hand but that doesn't seem to be working. You can see my feeble attempt in code below.
Questions:
1. Should I be Base64 encoding the image data in the body? If so, any base64 encoding suggestions? 2. Is this sort of thing even possible with NSURLConnection, or should i be using CFNetwork instead? 3. Should I be manually creating the multiple parts of the body like below, or should i just be allowing either NSURLConnection or CFNetwork to be doing the dirty work by itself?
any pointers to example code that shows how to do this would be awesome!
thanks!
Todd Ditchendorf
NSString *boundary = @"---------------foo"];
NSURL *url = "" URLWithString:@"http://example.com/myform"]; NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; [req setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data, boundary=%@", boundary];
[req setValue:contentType forHTTPHeaderField:@"Content-type"];
NSString *imagePath = @"/path/to/my/image/2088045786_c162978246.jpg"; NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
NSString *reqBodyStr = [NSString stringWithFormat:@"%@\nContent-Disposition: form-data; name=\"media_file\"; filename=\"2088045786_c162978246.jpg\"\nContent-Type: image/jpeg\n\n%@\n%@\n", boundary, imageData, boundary];
[req setHTTPBody:[reqBodyStr dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *res = nil; NSError *err = nil;
NSData *data = "" sendSynchronousRequest:req returningResponse:&res error:&err];
|
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Macnetworkprog mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden