I’ve had a couple people approach me and ask me how to POST to a web form with a mix of file data and other text values. After much research and lack of resources on the internet describing how to do so, I eventually stumbled upon a library, ASIHTTPRequest which makes it quite easy to do so.
Make sure you get the name attributes of all values you are trying to POST to your web service. In this particular web service, Blotify, we accept an image along with several values pertaining to the particular image. The file attribute is named media.
First, you want to translate your raw image data from the camera into a UIImage, and then into a NSData object. Secondly, set the URL to POST to.
NSData *imageData = UIImageJPEGRepresentation(image, 70);
NSString *urlString = [NSString stringWithFormat:@"http://api.blotify.com/upload/"];
Next, create your ASIFormDataRequest object and add the values you want to post to the server, making sure the keys align with the name attributes on the form of your web service, and send the request by sending the object a startSynchronous message. In this particular web service, we are accepting form values: details, rating, lat, lng, and media for the actual file.
ASIFormDataRequest *asiRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
[asiRequest addPostValue:@"in the lab" forKey:@"details"];
[asiRequest addPostValue:@"3" forKey:@"rating"];
[asiRequest addPostValue:@"35.296574" forKey:@"lat"];
[asiRequest addPostValue:@"-120.668886" forKey:@"lng"];
[asiRequest addData:imageData withFileName:@"image.jpg" andContentType:@"image/jpeg" forKey:@"media"];
[asiRequest startSynchronous];
To make debugging easier, you may want to log any messages the server responds with as such:
NSError *error = [asiRequest error];
if (!error) {
NSString *response = [asiRequest responseString];
NSLog(@"upload response: %@", response);
}
Here is a sample form this code coule be POSTing to, this may not be necessary, in the case that you are writing the back end to your own web service.
<form action="http://api.blotify.com/upload/" method="post" enctype="multipart/form-data">
Details: <input type="text" name="details" /><br>
Rating: <input type="text" name="rating" /><br>
Latitude: <input type="text" name="lat" /><br>
Longitude: <input type="text" name="lng" /><br>
<input type="file" name="media" /></br>
<input type="submit" name="submit" value="Upload" />
</form></code>
There you have it, with very minimal amount of code, you can start posting files and values to your favorite web services from iOS using the ASIHTTPRequest library! There is much more you can do with the library, I have just touched the surface with this post. If you would like to read more about the capabilities of this library, check out their wonderful documentation!


DeviantART
Last.FM
LinkedIn
StumbleUpon
Yelp
if i knew what you were saying…this would be helpful! haha i love you!