Created
December 30, 2008 16:36
-
-
Save robin/41659 to your computer and use it in GitHub Desktop.
cocoa http upload
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
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