I'm using NSMutableURLRequest to upload an image to a web server. I thought my code was stable as it works for the majority of users, but some users simply cannot upload any images. Looking at my server logs, I see the occasional
"Missing boundary in multipart/form-data POST data in Unknown on line 0" warning which would point to a boundary error in constructing the post body.
Below is what I'm using:
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:[method uppercaseString]];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data, boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-type"];
NSMutableData *postBody = [NSMutableData data];
// add the image
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"image_upload\"; filename=\"upload.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSData *jpegData = UIImageJPEGRepresentation(jpeg, 100);
[postBody appendData:jpegData];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// add the other POST params
keys = [postdata allKeys];
int l = [keys count];
for (int i=0; i<l; i++){
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", [keys objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[postdata objectForKey:[keys objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
I can understand if the code resulted in the PHP warning 100% of the time, but it probably occurs once in every 30 or 40 users. If a user gets this error, its the same for any image they try to post.
Can anyone see anything immediately obvious, or have any insights as to why this would be an intermittent problem?
Turns out the problem was with this line:
[request setValue:contentType forHTTPHeaderField:@"Content-type"];
It of course should be:
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
(note the case). Still not sure why this broke the request for only a small number of users, though.