This function is supposed to upload an UIImage to an web form per HTTP Post. I used extracts from some posts here and on othe rsites and got to this in the end.
But it doesn't work, it workes like an GET Method for url, at least for me. Could you pelase test it, too, or help me, where the mistake could be?
I DON'T want to use a framework like ASIHTTPRequest please.
- (NSString *)postImage:(UIImage *)image toURL:(NSURL *)url {
NSData *imageData = UIImagePNGRepresentation(image);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithFormat:@"---------------------------%i", (int)[[NSDate date] timeIntervalSinceReferenceDate]*100];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"Photo\"; filename=\"ipodfile.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField: @"Content-Length"];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
return [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
}
Thanks, Vincento
Are you sure that the image you are sending is not null? If you are trying to send an empty POST data it will be changed back to GET.
}
Seems all are ok. (Is all are ok on server side) ? I had put working example on http://code.developwithus.com/iphone/upload-image-and-data-with-iphone-sdk/ , will you try that?