How to send xml or image data from iphone to a rails 3 server? – Education Career Blog

I am developing a hybrid app (rails 3 + iPhone) and I want to send a number of large strings and images to a rails 3 server. I want to do a POST method from iPhone. Can someone help me on how to do this ? since in this case there will be no form in the views how should I accept the data ? Thanks in advance

,

Here is some code for uploading an image through POST to an URL:

UIImage *myImage = UIImage imageNamed:@"example.png";

NSData *imageData = UIImageJPEGRepresentation(myImage, 0.9);

NSString *url = NSURL URLWithString:@"http://postingurl.com/posthere";

NSMutableURLRequest *request = NSMutableURLRequest alloc init;
request setURL:url;
request setHTTPMethod:@"POST";

NSString *boundary = @"---------------------------14737809831466499882746641449";
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 stringWithString:@"Content-Disposition: form-data;     name=\"fileid\"; filename=\"myfile.png\"\r\n"
               dataUsingEncoding:NSUTF8StringEncoding;
body appendData:NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding;
body appendData:imageData;
body appendData:NSString stringWithFormat:@"\r\n--%@--\r\n",boundary dataUsingEncoding:NSUTF8StringEncoding;

request setHTTPBody:body;

NSData *returnData = NSURLConnection sendSynchronousRequest:request returningResponse:nil e    rror:nil;
request release;

//Log return..
NSString *returnString = NSString alloc initWithData:returnData encoding:NSUTF8StringEncoding;
NSLog(returnString);
returnString release;

You add more lines for Content-Disposition to include other fields.

Leave a Comment