I used the following code to PUSH an image and data into a server. The data is being sent but the image is not received in the server. Can someone spot me if there is an error in my below code which I have used:
NSString *urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:#"%#action=savesign",MainURL]];
// set up the form keys and values (revise using 1 NSDictionary at some point - neater than 2 arrays)
NSArray *keys = [[NSArray alloc] initWithObjects:#"user",#"poll",nil];
NSArray *vals = [[NSArray alloc] initWithObjects:user,pollid,nil];
// set up the request object
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
//Add content-type to Header. Need to use a string boundary for data uploading.
NSString *boundary = #"0xKhTmLbOuNdArY";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//create the post body
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
//add (key,value) pairs (no idea why all the \r's and \n's are necessary ... but everyone seems to have them)
for (int i=0; i<[keys count]; i++) {
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",[keys objectAtIndex:i]] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",[vals objectAtIndex:i]] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
}
[body appendData:[#"Content-Disposition: form-data; name=\"image\"\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[NSData dataWithContentsOfFile:pngFilePath]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
NSData *imageData = UIImagePNGRepresentation(_Signfield.image);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"myPngFile.png\"\r\n", _Signfield.image] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// set the body of the post to the reqeust
[request setHTTPBody:body];
// 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 the response from the server
{"status":"failure","error":[],"user":0}
And when I login and check the data is there but not the image.
When you perform a file upload via HTTP POST, the data that gets transmitted over the wire looks like this:
POST /upload HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, compress
Content-Length: 17918
Content-Type: multipart/form-data; boundary=0xKhTmLbOuNdArY
Host: example.com
User-Agent: HTTPie/0.7.2
--0xKhTmLbOuNdArY
Content-Disposition: form-data; name="user"
Diphin-Das
--0xKhTmLbOuNdArY
Content-Disposition: form-data; name="poll"
1
--0xKhTmLbOuNdArY
Content-Disposition: form-data; name="image"; filename="myPNGFile.png"
Content-Type: image/png
[Binary PNG image data not shown]
--0xKhTmLbOuNdArY--
The first seven lines are the HTTP headers that describe the request to server, including:
The HTTP request method (POST)
The resource being requested (/upload)
The HTTP protocol version (HTTP/1.1)
The length of the request body (Content-Length: 17918)
The type of data included in the request body (Content-Type: multipart/form-data; boundary=0xKhTmLbOuNdArY)
That last one is interesting. By setting the content type to multipart/form-data, we're allowed to include a mix of different data types into the request body. The boundary tells the server how each of the form values are separated in the request body.
The form values in the request body are described using a simple structure:
--[boundary marker]
Content-Disposition: form-data; name="[parameter name]"
Content-Type: [parameter value MIME type]
[parameter value]
The Content-Type header is optional if the parameter value is alphanumeric, but for other data types (images, videos, documents, etc.) it's required. The end of request body is signaled by a terminating boundary marker which is a standard boundary marker suffixed with a double-hyphen, e.g. --0xKhTmLbOuNdArY--. New line characters (\r\n) are used to delimit the various elements of the content parts.
There can be other elements to the form values in a multipart POST request. If you're interested, you can read about them in RFC 2388.
In order to upload a file from an Objective-C, you need to craft the request body to that specification outlined above. I've taken the code from your question and refactored it to function correctly & added a few explanatory notes along the way.
NSDictionary *params = #{ #"user": user, #"poll": pollid };
NSData *imageData = UIImagePNGRepresentation(_Signfield.image);
NSString *urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:#"%#action=savesign",MainURL]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"0xKhTmLbOuNdArY";
NSString *kNewLine = #"\r\n";
// Note that setValue is used so as to override any existing Content-Type header.
// addValue appends to the Content-Type header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// Add the parameters from the dictionary to the request body
for (NSString *name in params.allKeys) {
NSData *value = [[NSString stringWithFormat:#"%#", params[name]] dataUsingEncoding:NSUTF8StringEncoding];
[body appendData:[[NSString stringWithFormat:#"--%#%#", boundary, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"", name] dataUsingEncoding:NSUTF8StringEncoding]];
// For simple data types, such as text or numbers, there's no need to set the content type
[body appendData:[[NSString stringWithFormat:#"%#%#", kNewLine, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:value];
[body appendData:[kNewLine dataUsingEncoding:NSUTF8StringEncoding]];
}
// Add the image to the request body
[body appendData:[[NSString stringWithFormat:#"--%#%#", boundary, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"myPngFile.png\"%#", #"image", kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: image/png"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#%#", kNewLine, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[kNewLine dataUsingEncoding:NSUTF8StringEncoding]];
// Add the terminating boundary marker to signal that we're at the end of the request body
[body appendData:[[NSString stringWithFormat:#"--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
Related
I am trying to upload multiple images to server in the form of array using NSURLConnection (multipart/form-data). But I am unable to send. Just one image is being sent to server even from the array of multiple images. I have tried many solutions, but nothing working for me. Server is written in Node.js.
NSString *first_name;
NSString *last_name;
NSString *image_name;
NSData *imageData;
//-- Convert string into URL
NSString *urlString = [NSString stringWithFormat:#"https://delta-homelab.com/api/order/test"];
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"];
//-- Append data into posr url using following method
NSMutableData *body = [NSMutableData data];
NSArray *imagesArray = [NSArray arrayWithObjects:[NSData dataWithData:UIImagePNGRepresentation([UIImage imageNamed:#"Pin Code"])],
[NSData dataWithData:UIImagePNGRepresentation([UIImage imageNamed:#"Pin Code"])],
[NSData dataWithData:UIImagePNGRepresentation([UIImage imageNamed:#"Pin Code"])], nil];
NSData *images = [NSKeyedArchiver archivedDataWithRootObject:imagesArray];
NSMutableData *postData = [NSMutableData dataWithCapacity:[images length] + 512];
[postData setData:images];
//-- For Sending text
//-- "firstname" is keyword form service
//-- "first_name" is the text which we have to send
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",#"firstname"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",first_name] dataUsingEncoding:NSUTF8StringEncoding]];
//-- "lastname" is keyword form service
//-- "last_name" is the text which we have to send
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",#"lastname"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",last_name] dataUsingEncoding:NSUTF8StringEncoding]];
//-- For sending image into service (send as imagedata)
//-- "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=\"images\"; filename=\"%#\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[NSData dataWithData:UIImagePNGRepresentation([UIImage imageNamed:#"Pin Code"])]];
[body appendData:postData];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",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 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.
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]];
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.
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 :)