Objective c - Send an image over http POST

Eyal picture Eyal · May 30, 2012 · Viewed 8.5k times · Source

I'm trying to understand how to send an image with http POST and my current client-server protocol design. All the messages from client to server looks like the example below, there is a cmd string with parameter cmd and some more relevant parameters for the command.

For example this is how i send a text message to the server:

- (void)sendMessagesWithText:(NSString *)text fromUser:(NSString *)userId
{
    NSString *url = SERVER_URL;

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];

    NSMutableData *body = [NSMutableData data];

    [body appendData:[[NSString stringWithFormat:@"cmd=%@&userid=%@&msgtext=%@", 
                       @"sendmessage", 
                       userId,
                       text] dataUsingEncoding:NSUTF8StringEncoding]];


    [request setHTTPBody:body];

    // send to server
    [[NetworkHelper sharedManager] sendRequest:request]; 
}

Now I want to enable the user to send also an image, but how do I send it with my protocol design? should i just append the image to the body after the cmd string?

Answer

Jeffery Thomas picture Jeffery Thomas · May 30, 2012

You need to post with multipart/form-data.

Here is the example from the now defunct ASI: Creating and running requests

Sending a form POST with ASIFormDataRequest

To send POST data in a manner compatible with web page forms, use the included ASIFormDataRequest subclass. Data is posted in ‘application/x-www-form-urlencoded’ format, or ‘multipart/form-data’ format when uploading binary data or files. Data in files is read as needed from disk, so POSTing large files is OK, as long as your web server is setup to handle them.

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

ASIFormDataRequest will autodetect the mime type of files (on iOS 3.0 or later an Mac) added to the POST via setFile:forKey:, and include this in the mime headers sent to the server. If you prefer, you can use the longer form to override this:


Multipart/form-data sucks. Trust me, I've implemented it in C++ a number of years ago. Get someone else to do the dirty work.

But if you still want to go it alone. I found this and this. Good Luck.