views:

39

answers:

2

I'm trying to upload an image file to a http server. Here's the code fragment

 NSData *imgData = UIImagePNGRepresentation(img);

 NSString *post = [NSString stringWithFormat:@"&UserID=%@&Query=%@&fileContent=", userID, @"putImage"];

 NSMutableData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

 [postData appendBytes:[imgData bytes] length:imgData_len];

 NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

 NSURL *url = [NSURL URLWithString:@"http://ryan.verifyidonline.com/test.php"];

 NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];

 [theRequest setHTTPMethod:@"POST"];

 [theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];

 [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];

 [theRequest setHTTPBody:postData];

 NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

This code only sends the first few characters of the image file. I think I have to encode the file somehow, but I haven't had any luck trying the NSString encodings.

A: 

http://www.cocoadev.com/index.pl?HTTPFileUpload

Good luck, it gave me a bit of trouble but based on the stuff here (you'll have to read through the bottom, fixed code was submitted over time) creating a clean, reusable way to do this shouldn't take too much time.

Jared P
A: 

There's not a chance of your code working like that. At the very least, you'd need to encode the image data in some way so that only ASCII characters (and then not %, &, = and white space) appear in the value for fileContent.

However, to do it properly, you have to create a multipart MIME body with correct content types etc. I think the code in the link of Jared's will work, but there might be a bug in the character set encoding. If you do not specify a charset in HTTP, ISO-8859-1 is assumed but the code seems to be using UTF-8 everywhere without saying the charset is UTF-8.

JeremyP