i want to upload image,video and audio files to a server. I have read this thread on the similar topic but wasn't able to understand completely the flow of the code. It would be great if you can suggest me some sample code or tutorial to start with. I am using the following code to connect without any media to the server
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *url =[[NSString alloc]initWithFormat:#"%#",[NetworkConstants getURL]];
NSURL *theURL =[NSURL URLWithString:url];
[url release];
NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0.0f];
[theRequest setHTTPMethod:#"POST"];
NSString *theBodyString = [NSString stringWithFormat:#"json1=%#&userID=%#",jsonObject,[GlobalConstants getUID]];
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:theBodyData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (conn) {
NSLog(#"Successful in sending sync");
}
else {
NSLog(#"Failed Connection in sending sync");
}
[conn release];
It would be really convenient for me if anything could be done editing this part of code.
Any form of help would be highly appreciated.
Thanks in advance!!
Although it is very early to answer my own question but I got the solution so thought of adding it up here.
To the above code we just need the following modification
NSData *imageData = UIImageJPEGRepresentation(attachedImage.image, 90);
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[theRequest addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *theBodyData = [NSMutableData data];
[theBodyData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[#"Content-Disposition: form-data; name= \"server_value_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[yourString dataUsingEncoding:NSUTF8StringEncoding]];
//this appends the image data
[theBodyData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"image\"; filename=\"1.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[[NSString stringWithString:#"Content-Type: image/jpg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[NSData dataWithData:imageData]];
[theBodyData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setHTTPBody:theBodyData];
And the rest remains the same as in Question.
One just need to remember while sending a Multi-Part Request that all the parameters required by the server need to go with in the boundary and every parameter should be send in individual boundaries.
Hope this helps the others as well.
:)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am sending data from iPhone application to server but when i submit form application crash.Please check code and suggest me advise thanks in advance.
-(IBAction)SAVE:(id)sender
{
NSString *post =[[NSString alloc] initWithFormat:#"amount=50&termid=1&state=%#&city=%#&post_title=%#&description=%#&post_price=10&post_location=asd&geo_latitude=%#&geo_longitude=%#&owner_name=%#&owner_email=abc#a.a&owner_phone=%#&post_tags=a&post_url=%#&coupon_code=a¤t_userid=1&type=renew",txt4.text,txt5.text,txt6.text,latValue,longValue,txt7.text,txt8.text,txt9.text,txt10.text];
NSLog(#"String Posted:%#",post);
NSURL *url=[NSURL URLWithString:#"http://www.Example.com.mx/testing/publication.php?"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
con=[NSURLConnection connectionWithRequest:request delegate:self];
if(con){
responseData=[NSMutableData data];
}
}
-(void)uploadDataToServer
{
//Server Address URL
NSString *urlString = [NSString stringWithFormat:#"Your Server Address"];
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"];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter first
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//Attaching the key name #"parameter_first" to the post body
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter_first\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//Attaching the content to be posted ( ParameterFirst )
[body appendData:[[NSString stringWithFormat:#"%f",ParameterFirst] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter second
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//Attaching the key name #"parameter_second" to the post body
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter_second\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//Attaching the content to be posted ( ParameterSecond )
[body appendData:[[NSString stringWithFormat:#"%f",ParameterSecond] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter third
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//Attaching the key name #"parameter_third" to the post body
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter_third\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//Attaching the content to be posted ( ParameterThird )
[body appendData:[[NSString stringWithFormat:#"%d",ParameterThird] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"Request = %#",[[NSString alloc] initWithData:body encoding: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 %#",returnString);
NSDictionary* jsonResponse = [CommonFunctions parseJSON:returnData];
NSLog(#"Json responce %#",jsonResponse);
if ([[jsonResponse objectForKey:#"replyCode"] isEqualToString:#"success"])
{
isSuccessfulPost=YES;
}
else
{
isSuccessfulPost=NO;
}
}
Hope the answer is useful for you . You can increase/decrease the number of paramter by simply altering the body
Please add code to check.
In iOS applications I suggest using AFNetworking
for any server - client communication.
I am trying to upload some data to web service using post action
But the following error happens on didReceiveData.
400 Bad Request
a 404 Not Found
Can you please help me on this coding issue?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
NSMutableData *postData = [[NSMutableData alloc] init];
NSString *boundary = [NSString stringWithString:#"------------------147378098Aadfsn1987XdaoTwq"];
// First name
[postData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[#"Content-Disposition: form-data; name=\"firstname\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[firstName dataUsingEncoding:NSUTF8StringEncoding]];
NSData *photo = UIImageJPEGRepresentation(takePhoto, 0.5f);
// Photo data
[postData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[#"Content-Disposition: form-data; name=\"picture1\"; filename=\"photo.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
if (takePhoto != nil) {
[postData appendData:photo];
}
NSString *postLength = [NSString stringWithFormat:#"%d", postData.length];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Try this Code For Uploading Photo to Server From iPhone.
- (IBAction)uploadImage {
/*
turning the image into a NSData object
getting the image back out of the UIImageView
setting the quality to 90
*/
NSData *imageData = UIImageJPEGRepresentation(image.image, 90);
// setting up the URL to post to
NSString *urlString = #"Your URL string where you want to POST Photo";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"rn--%#rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name="userfile"; filename="ipodfile.jpg"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"rn--%#--rn",boundary] 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);
}
Those are server errors not iPhone errors. your sending a bad URL or your service is not reading your url properly.
Your url is probably not encoded. Try something like this..
NSString* url =
[#"http://your-url-.com" stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
Im trying to build an application that will record voices (mic) on my iPhone,
and then will send them to store on my server.
can anyone help me with this one.
i even don't know where to began with this :)
Thank you very much,
Oded.
Just google it "how to record iphone" and you get it in a seconds.
After recording, file will create in your Documents folder.
Retrieve that path and extract data in NSData and send to server through POST method.
Sample code,
NSLog(#"SendingRecordedData");
NSString *urlString = [NSString stringWithFormat:#"http://your_server/fileupload.php"];
NSLog(#"Url:%#",urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------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=\"pics\"; filename=\"record.caf\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data2]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
there is sample code with recording - SpeakHere on iOS developer site. After recording you can save it and send as any binary file.
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.
I am doing some uploading stuff in iphone this time. This is absolutely first time for me.
I have found some useful links and answers by googling and finding them on stackoverflow.
And I was able to upload an image by the following code :
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
NSString *urlString = #"server-url";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]init] autorelease];
[request setTimeoutInterval:60.0];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------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=\"file\";filename=\"myfile.jpg\"\r\n"]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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]];
//NSString * dataLength = [NSString stringWithFormat:#"%d", [body length]];
//[request addValue:dataLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:body];
NSLog(#"%#",[[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding]);
But I have lots of questions on the how the above code works like what is boundary and what is the format for it What is content disposition and other things as well .
I have googled a lot for understanding the format for a post request but found nothing then ready code If anyone knows some good tutorial or exmples on how a post request format is build in iphone then please provide so i can understand how the above code will work ?
you can look at the documentation on returning values from forms with POST here.
https://www.rfc-editor.org/rfc/rfc2388
like you said, the code works, this is a document explaining what you see and what it all means