sending a body in a form of form-data - ios

i have a post request, were i should send a body in the request, but it should be in the form of form-data:
the data are now in an nsmutable dictionary as follow :
contacts (
{
Images = (
"http://otrackapi.omegasoftware.ca/ActStaff/public/uploads/user-image-94.jpg"
);
"company_name" = tttt;
"contact_email" = "tttt#me.com";
"contact_fname" = tttt;
"contact_lname" = tttt;
"contact_phone" = 1323223;
lat = "37.330434";
lng = "-122.030163";
remark = Tttt;
"type_id" = 18;
}
)
they should be as form-data as below:
contants[0][contact_name]: bla
contacts[0][comtact_email]:blabla
etc...
if you have postman, you can see it its clearer there,
any idea how to convert it?
thanks

I will suggest, try using Alomofire.try to create your JSON and send it to your parameter by a converting it to base64string and tell the Backend guys to decode it then they can get the value.

Try below answer,
// your url
NSString *urlString = #"http://www.somesite.com/public/api/v1/create
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
Now for adding parameters
// api key parameter: here parameter is 'api' its value is 1
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"api_key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"1" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// here parameter is 'subject' and value is taken from '_subjectView.text'
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"subject\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[_subjectView.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
// your rest code
like this, you can add multiple parameters with value in the body.
If you want to check boundary in postman see below images,
in postman screen, you may look like this image. In the top right corner, there is one button "Code" click on that button, you will get one pop-up like below image.
check here boundary value.

Related

IOS: getting '400 Bad Request' when using multipart/form-data

I am new IOS developer and I am facing a headache issue regarding to use multipart for uploading file and some text, i have tried a lot on here
The status code always return 400. I tired to test my web service with another way, such as build Rest client by HttpComponent API, using RestEASY client and both of them worked successfully, how funny!
I am using Xcode 6.1.1, my source code:
-(void)uploadPhoto {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://localhost/my-rest-service"]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"avatar_temp"], 1.0);
NSString *boundary = #"12345-6789-abc"; //
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
[body appendData:[[NSString stringWithFormat:#"%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#\r\n\r\n", #"type"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", #"HELLO"] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the request
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if(data.length > 0){
//success
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"[String] %#", str);
}
}];
}
Any suggestions will help my investigation
Thanks
An
You forgot to add imageData so add:
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
A full working example:
[request setHTTPMethod:#"POST"];
NSData *imageData = UIImageJPEGRepresentation(imageToSave,0.9); //change imageToSave with your own UIImage defined
NSString *filenames = #"first field";
NSString *token = #"second field";
NSString *boundary = #"---------------------------14738723651466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
////+++ first form field for post -> for example a field called filenames see NSString above
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"filenames\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[filenames dataUsingEncoding:NSUTF8StringEncoding]];
////--- the second field for form post-> we named token see above NSString
////+++
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"token\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[token dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
////---
////+++ the file used to upload /post
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"ceva.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
////---
// setting the body of the post to the reqeust
[request setHTTPBody:body]; // now lets make the connection to the web
Now all the you want to make is check your php code on server side.

iOS-Upload image to OneDrive using REST API

I am trying to upload image from my app to onedrive using the REST api they provided.
But missing some formating for PST method, please help to work out.
I am doing as,
NSString *urlString = [NSString stringWithFormat:#"https://apis.live.net/v5.0/me/skydrive/files?access_token=%#",oneDriveAccessToken];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"A300x";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//-- Append data into post url using following method
NSMutableData *body = [NSMutableData data];
//-- "image_name" is file name of the image (we can set custom name)
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"file\"; filename=\"%#\"\n",#"name.JPG"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\n\r\n\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:#"--%#--",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//-- Sending data into server through URL
[request setHTTPBody:body];
//-- Getting response form server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
I am getting response as:
Result = {
error = {
code = "request_body_invalid";
message = "The request entity body for multipart form-data POST isn't valid. The expected format is:
\n--[boundary]
\nContent-Disposition: form-data; name=\"file\"; filename=\"[FileName]\"
\nContent-Type: application/octet-stream
\n[CR][LF]
\n[file contents]
\n--[boundary]--[CR][LF]";
};
}
I am following this http://msdn.microsoft.com/en-us/library/hh826531.aspx#uploading_files
After suggestions of Jeffery, error message as,
Result = { error = { code = "request_body_invalid"; message = "The
request entity body has an incorrect value in the 'Content-Disposition'
header. The expected format for this value is 'Content-Disposition: form-
data; name=\"file\"; filename=\"[FileName]\"'."; }; }
As a guess, you are mangling the line endings. Sometimes you are using \n sometimes \r\n. You must always use \r\n. As a side note, you shouldn't need the initial \r\n on your first -appendData call. Finally, check your boundary string: they are usually longer to avoid the having those exact same bytes in the content.
NSString *boundary = #"A300x-make-it-longer-to-reduce-risk-12345";
…
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"file\"; filename=\"%#\"\r\n", #"name.JPG"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:#"--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

I am uploading one file successfully by using following code how can i use the same code upload 3 file. I do not want to use code again again

NSString *filenames = [NSString stringWithFormat:#"front_img"];
NSString *urlString = #"http://ccccc.com/upfile.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[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 stringWithFormat:#"Content-Disposition: form-data; name=\"filenames1\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[filenames1 dataUsingEncoding:NSUTF8StringEncoding]];
/*Sending First Image start here*/
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n", filenames]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData1]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
/*Sending First Image ends here*/
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",returnString);
A typical upload http body will look like:
--BOUNDARY_TEXT
Content-Type/Content-Disposition info key values
Base64 encoded file data ...
--BOUNDARY_TEXT
Content-Type/Content-Disposition info key values
Base64 encode file data.
--BOUNDARY_TEXT
You've done the first one, just continue append files according to the format seperatored by the BOUNDARY.

Uploading image to server via node.js from an iOS app

I am developing an iOS app and I am using node.js for server side scripting. I am facing problem in uploading image to server from iOS app. It is working fine if I am uploading image from webpage form. But if uploading from app side it is not working.
//test file
h3 Pic Upload
form(action='/pic_upload', method='post',enctype='multipart/form-data')
| user_pic:
input(type='file', name='user_pic')
input(type='submit')
//app.js
var userlogin =require('./routes/userlogin');
app.post('/pic_upload', userlogin.picUpload);
//userlogin.js
//picUpload function
exports.picUpload = function(req, res) {
console.log(req.files); // showing undefined, when called from IOS app
// pic upload script...
});
I have tried sending image from app side as data or file parameter but it did not work. How to send the file parameter from app side so that I can easily upload the image to server? Kindly suggest a way to tackle the problem.
This code works in my app. Try this.
NSData *imgData = UIImageJPEGRepresentation(newImg, 0.2);
NSString *str = #"displayImage";
NSString *urlString = #"http://some.url.com/post";
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithFormat:#"---------------------------14737809831464368775746641449"];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"currentEventID\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"52344457901000006" dataUsingEncoding:NSUTF8StringEncoding]];
// add image data
if (imgData) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"displayImage\"; filename=\"image.jpg\"\r\n"]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", str] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imgData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set URL
[request setURL:[NSURL URLWithString:urlString]];
NSString *bodyStr = [[NSString alloc]initWithData:body encoding:NSUTF8StringEncoding];
NSLog(#" %#",bodyStr);
NSURLConnection *lot_Connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
if(lot_Connection)
{
webdata = [[NSMutableData alloc] init];
}

Sending a UIImage and text to server

I have a simple question- I'm currently writing a specific part in my app related to sending data to server.
I tried to send text, succeeded. Sent image, succeeded.
What I'm trying to do now is to send them both within one POST request.
I figured out that I need to use something that is called multipart/form-data and boundaries, but I haven't found anymore info about it.
So how can I send both text and image in one, simple POST request? And how can I check for errors during upload, afterwards etc.?
Thanks!
Reference code I've written but sending 0 bytes of info:
NSData *imageData = UIImageJPEGRepresentation(sendImage, 1.0);
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://posttestserver.com/post.php?dir=something"]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------54737809831466490885746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"rn--%#rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\"reportingImage.jpg\"rn" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-streamrnrn" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"rn--%#--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: text/xml" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[[alertView textFieldAtIndex:0] text] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
This is a working snippet that sends text and image, optionally a few texts with a few params per each
//After dismissing the alert, we get its text (user location and notes) and the picture he took
NSMutableData *body = [NSMutableData data];
NSURL *url = [NSURL URLWithString:#"http://posttestserver.com/post.php?dir=Doda"]; //Test server, you can access it online to see the upload
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449"; //I have no idea what this is, but without it the code won't work
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[req setValue:contentType forHTTPHeaderField: #"Content-Type"];
//Attaching image
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"imageOfReport\"; filename=\"imageOfReport.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:UIImageJPEGRepresentation(sendImage, 1.0)]]; //Crucial, getting a JPEG version of the image and sending it
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"report_description\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[[alertView textFieldAtIndex:0] text] dataUsingEncoding:NSUTF8StringEncoding]]; //Crucial, taking the text from the Alert and sending it
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:body];
//Below are few lines which can add other parameters and text
/* [body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"spid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:body];*/
NSURLConnection *sendingTheData2 = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES]; //Sent! ;)
You probably want to use a network library like AFNetworking, and save yourself some time :)

Resources