robin (owner)

Revisions

gist: 41659 Download_button fork
public
Description:
cocoa http upload
Public Clone URL: git://gist.github.com/41659.git
Embed All Files: show embed
Objective-C #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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];