I am working on a project (that i will not be releasing to the app store - just for fun) that will upload an image via an HTTP Post request from my iPhone to a server that I have running the Python script SimpleHTTPServer(http://ubuntuguide.net/http-server-support-uploading-files-from-windows-in-ubuntu). I have successfully used the ASIHTTP APIs in the past for text strings, but can't for the life of me figure out how to upload an image. This is what I am currently using:
-(void)processRequest {
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"mySimpleHTTPServer"]];
[request setFile:[UIImage imageNamed:@"Image.png"] withFileName:@"Image.png" andContentType:@"image/png" forKey:@"file"];
[request startSynchronous];
NSLog(@"%@",[request responseString]);
NSUserDefaults *profiles = [NSUserDefaults standardUserDefaults];
[profiles setObject:[request responseString] forKey:@"response"];
[profiles synchronize];
[self performSelector:@selector(endRequest) withObject:nil afterDelay:0];
}
Really, the only part that I am assuming I am wrong about is the :
[request setFile:[UIImage imageNamed:@"Image.png"] withFileName:@"Image.png" andContentType:@"image/png" forKey:@"file"];
Any thoughts on where i could be going wrong?
As @SorinA. mentions, you should supply a file path as the first argument to setFile:withFileName:andContentType:forKey:. In your example, you're supplying a UIImage object instead.
The simplest fix, however, might be to just use setData:withFileName:andContentType:forKey:. You just need to convert your UIImage object to its NSData representation:
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"Image.png"]);
[request setData: imageData
withFileName: @"Image.png"
andContentType: @"image/png"
forKey: @"file"];
Also, your URL looks a bit odd ("mySimpleHTTPServer"), I assume this is just a placeholder for a URL in the form of "http://localhost:some_port/some_path"? Definitely confirm that your Python web server is actually seeing the request.
Offhand, I don't see an obvious problem, but I would try calling [request responseStatusCode] and [request responseStatusMessage] instead of [request responseString]. I'm guessing that the the response to a post would not have a string. I think it should return 200 or something like that to indicate success.
You can also try:
if(request.error) {
NSLog("ERROR: %@",[error localizedDescription]);
}
Lastly.. I would look at ASIHTTPRequestConfig.h I'm using ASI as well, so I just peeked at it and it has some debug options that should help.
set the 0's to 1s:
DEBUG_FORM_DATA_REQUEST 1
DEBUG_REQUEST_STATUS 1
If you haven't tried those, that should give you some info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With