How to post (HTTP POST) zipfile and parameters in ObjectiveC? - iphone

I have tried to Post a Zipfile and some parameters to web service, but i get the response "missing ebook file", so how to Post zip file and parameters in Objectivec please help me
Thanks in Advance
I have tried this:
NSString *urlString1 = [NSString stringWithFormat:#"http://www.EbookFile.com/index.php?q=api/upload&APPkey=dfsfwerwe324342323432"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString1]];
[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];
// Parameter 1
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"uid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[uid dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Parameter 2
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[titleText.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Parameter 3
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"token\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[token dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Parameter 4
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"desc\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[descText.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Parameter 5
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"cat\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[CatId dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// ZIP File Post here
int r = arc4random() % 8000000;
NSString *RandomNumber = [NSString stringWithFormat:#"%d",r];
NSString *file = [RandomNumber stringByAppendingString:#".zip"];
NSData *Filedata = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:archivePath]]; // ZIP file convert to NAData here
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: attachment; name=\"file\"; filename=\"%#\"\r\n",file] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:Filedata];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// pointers to some necessary objects
NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init];
NSError* error = [[NSError alloc] init] ;
// synchronous filling of data from HTTP POST response
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
{
}
NSString *responseString = [[[NSString alloc] initWithBytes:[responseData bytes]
length:[responseData length]
encoding:NSUTF8StringEncoding] autorelease];

First, there are different styles of web services, and you haven't specified which you're dealing with. Is it a SOAP-based service? REST? XML-RPC? For the sake of discussion, I'll assume it's a RESTful service, since that's where most people seem to be going these days.
The problem I see is that you're trying to put the parameters in the body of the post. You'll have to check the documentation for the specific API that you're using, but usually parameters are provided either as query parameters in the URL that you're posting to, or specified in the headers that you send in the request. The body of the request should be the zipped data.

Try to Send the file your file in this way
NSUInteger length = [myData length];
NSData *filedata;
Byte *byteData = (Byte *)malloc(length);
[data getBytes:byteData length:length];
[postbody appendBytes:(const void *)byteData length:length];

NSString *urlString1 = [NSString stringWithFormat:#"http://www.efferwrwre.com/index.php?q=api/upload&key=f5746442fb9067b3fba83c3da0351f1f"];
NSLog(#"URLSTribg : %#", urlString1);
NSString *ww = [urlString1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:ww]];
[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=\"uid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[uid dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[titleText.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"desc\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[descText.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"cat\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[CatId dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
int r = arc4random() % 8000000;
NSString *RandomNumber = [NSString stringWithFormat:#"%d",r];
NSString *file = [RandomNumber stringByAppendingString:#".zip"];
NSData *Filedata = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:archivePath]];
NSLog(#"file:%#",Filedata);
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n",file] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:Filedata];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init];
NSError* error = [[NSError alloc] init] ;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
{
}
NSString *responseString = [[[NSString alloc] initWithBytes:[responseData bytes]
length:[responseData length]
encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"%#", responseString);

Related

How to do specific HTTP POST in objective c (working curl line included)?

My API needs to receive some parameters and image via HTTP POST. In curl it is done with:
curl http://someurl -F 'service[lat]=12.22' -F 'sevice[lng]=12.33' -F 'service[user_id]=4' -F 'service[location]=Vienna' -F 'service[image]=#tour.jpg'
How can it be done in objective C (iphone)?
I guess it be done with content type set to "application/x-www-form-urlencoded"?
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"random string of your choosing";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// file
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"name\"; filename=\"%#\"\r\n", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// length
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"size\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%i",imageData.length] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// lat
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"lat\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%f",lat] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// lon
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"lon\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%f",lon] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// location
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"location\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:location] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// user_id
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"user_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:user_id] 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];
//bon voyage
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
I suggest you take a look at the ASIHTTPRequest framework if you want to avoid the hassle of building the post data yourself.
Example from documentation :
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"Ben" forKey:#"names"];
[request addPostValue:#"George" forKey:#"names"];
[request addFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photos"];
[request addData:imageData withFileName:#"george.jpg" andContentType:#"image/jpeg" forKey:#"photos"];
I use it in all my projects, it's very robust and easy to use.
Please do NOT use ASIHTTPRequest. From the developer's homepage:
Please note that I am no longer working on this library - you may want to consider using something else for new projects. :)
I've heard good things about AFNetworking
But implementing POST Requests via NSURLRequest is not that hard and you do not depend on another library.

NSURLRequest setHttpBody

I got a wrong post(php:echo $_POST) like below:
Array ( [email"aa#qq_com] => -----------------------------14737809831466499882746641449 Content-Disposition: form-data; name="password" c8837b23ff8aaa8a2dde915473ce0991 )
my code:
// set header value , some random text that will never occur in the body
NSString *boundary = #"---------------------------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]; // email part
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"email\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[anEmail dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; // password part [body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"password\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[aPassword dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; // image part [body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat: #"Content-Disposition: form-data; name=\"uploadingImage\"; filename=%#\r\n", anImageName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:aFileData]];
[body appendData:[#"\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]; // now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
it should be
name=\"password\"\r\n\r\n%#",password];
but now you are doing like this
name=\"password\"\r\n%#\r\n",password];
Hope you understood the mistake..

Form post in IPhone app not working

I am trying to post values & file over HTTP in an IPhone app.
The requirement is when the form is posted, the values in the input boxes has to be used for authentication and if the user is valid, the file should get uploaded.
But when I try to post the form, the file is not getting posted and also the posted values are not accepted by the action URL.
Find below the code used in the IPhone app and its HTML equivalent. Can someone tell what I am missing?
HTML Equivalent
<form action="http://www.something.com/upload/" method="post" enctype="multipart/form-data" target="_blank" onsubmit="return window.confirm("You are submitting information to an external page.\nAre you sure?");">
<h3>Test Form</h3>
<p>File: <input name="file" type="file"></p>
<p>Username: <input name="usr" type="text"></p>
<p>Password: <input name="pwd" type="text"></p>
<p><input name="send" value="Upload" type="submit"></p>
</form>
Code used in IPhone app
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"test-upload" ofType:#"zip"];
NSData *postData = [NSData dataWithContentsOfFile:filePath];
NSString *urlString = #"http://www.something.com/upload/";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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:[#"Content-Disposition: form-data; name=\"usr\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"usr#domain.com" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"pwd\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"testpwd" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"test-upload.zip\"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:postData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",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);
Looks like you've got a problem with this line:
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"test-upload.zip\"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
Shouldn't that be:
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"test-upload.zip\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
?
Finally solved by correcting the boundary. I have posted the whole code below
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"test-upload" ofType:#"zip"];
NSData *postData = [NSData dataWithContentsOfFile:filePath];
NSString *urlString = #"http://www.something.com/upload/";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"usr\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"user#domain.com" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"pwd\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"testpwd" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"test-upload.zip\"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:postData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",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);

Uploading videos to twitpic

-(IBAction)pushUpload{
NSData *media = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Movie" ofType:#"m4v"]];
NSString *urlString = #"http://api.twitpic.com/api/upload";
NSString *key = #" ";
NSString *message =messagetext.text;
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *username = [prefs stringForKey:#"keyToLookupString"];
NSString *password = password.text;
NSUserDefaults *prefs2 = [NSUserDefaults standardUserDefaults];
[prefs2 setObject: password forKey:#"keyToLookupString2"];
// username part
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"username\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[username dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// password part
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"password\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[password dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// key part
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[key dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// message part
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"message\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[message dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//media part
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"media\"; filename=\".m4v\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:media]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"response is:%#",returnString);
}
` I am trying to uplaod video file to the specified url of twit pic which helps the user to upload their videos to twitter. When i press button video file should upload into the url which i used. but when i check,getting a response that the page you requested could not be found.Has anyone tried to upload videos to twit pic. Please give me some sample codes.Thanks in advance.
the error is related to the incorrect urlString. I also dont see which twitpic-api-version you are using.
twitpic-api-version-2 (latest api-version this should be used) needs authorization first via OAuth and api-key, message and media as parameters
urlString should look like: http://api.twitpic.com/2/upload.xml
twitpic-api-version-1 (not the latest one: only there because of compability. Will be shut down sometime in future) needs the parameters you added but also two additional oauth-parameter which are missing in your body.
urlString should look like: http://api.twitpic.com/1/upload.xml

Objective C: How to upload image and text using HTTP POST?

I've successfully created two different methods where each of them can upload either an image or text. But I am having problem writing a method that can post both text and image simultaneously!
// Here's my new method witch worked fine thanx to #sgosha:
- (void) upload {
NSString *urlString = #"http://www.examplescript.com";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// file
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: attachment; name=\"userfile\"; filename=\".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 stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Text parameter1
NSString *param1 = #"parameter text";
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter1\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Another text parameter
NSString *param2 = #"Parameter 2 text";
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter2\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param2] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
//Old question:
Obviously this was too easy and didn't work! I do not get any error in the console or anything, and the image is uploaded, but the text is not sent. Any ideas?
Btw: The server-side script is a very simple php script.
Try this (EDITED):
NSMutableData *body = [NSMutableData data];
// file
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: attachment; name=\"userfile\"; filename=\".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 stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// text parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter1\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[parameterValue1 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// another text parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter2\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[parameterValue2 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
I also wanted to upload an image along with other data in the same POST, most information about uploading images is just for uploading an image alone in one server connection, here is how I solved this.
This is the PHP
<?php
/* As you can see there are more values not only the image */
$variableOne = $_POST['variableOne'];
$variableTwo = $_POST['variableTwo'];
$variableThree = $_POST['variableThree'];
$variableFour = $_POST['variableFour'];
$variableFive = $_POST['variableFive'];
$variableSix = $_POST['variableSix'];
$variableSeven = $_POST['variableSeven'];
$variableEight = $_POST['variableEight'];
$variableNine = $_POST['variableNine'];
$variableTen = $_POST['variableTen'];
/* Our image */
$image = $_REQUEST['image'];
/* This is for trying to get a unique name for the image file, since maybe you want to store large amount of images */
$currentDate = date("Y-m-d");
$name = "" . $currentDate . microtime() . rand(0, 999) . rand(0, 999) . rand(0, 999) . ".jpg";
/*
* Here comes the image stuff
*/
if (file_exists($name)) {
echo "File already exists";
} else {
/* Decoding image */
$binary = base64_decode($image);
/* Opening image */
$file = fopen($name, 'wb');
/* Writing to server */
fwrite($file, $binary);
/* Closing image file */
fclose($file);
echo "Added";
}
}
?>
Then in Xcode copy and paste this method (taken from Creating a base-64 string from NSData)
- (NSString*)base64forData:(NSData*) theData {
const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length];
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
NSInteger j;
for (j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger theIndex = (i / 3) * 4;
output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
In YourViewController.h file
#interface YourViewController : UIViewController {
NSURLConnection *serverConnection;
NSMutableData *returnData;
}
This is the server connection code
NSURL *sendURL = [NSURL URLWithString:#"http://yourdomainname/imagefolder/phpscript.php"];
NSMutableURLRequest *sendRequest = [NSMutableURLRequest requestWithURL:sendURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[sendRequest setHTTPMethod:#"POST"];
[sendRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *imageData = UIImageJPEGRepresentation(yourImage, 1.0);
NSString *encodedString = [[self base64forData:imageData] stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSString *dataToSend = [[NSString alloc] initWithFormat:#"variableOne=%#&variableTwo=%#&variableThree=%#&variableFour=%#&variableFive=%#&variableSix=%#&variableSeven=%#&variableEight=%#&variableNine=%#&variableTen=%#&image=%#", valueOne, valueTwo, valueThree, valueFour, valueFive, valueSix, valueSeven, valueEight, valueNine, valueTen, encodedString];
[sendRequest setHTTPBody:[dataToSend dataUsingEncoding:NSUTF8StringEncoding]];
serverConnection = [[NSURLConnection alloc] initWithRequest:sendRequest delegate:self];
[serverConnection start];
Set delegate methods for server connection
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
returnData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[returnData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == serverConnection) {
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#", responseString);
if ([responseString isEqualToString:#"Added"]) {
/* Make something on success */
} else {
/* Make something else if not completed with success */
}
}
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
/* Make something on failure */
}
This code works for me with 1 image and 7 other parameters using POST Request
Make sure to change your variable names plus values and also image parameter name plus 'showPhoto' which is my IBOutlet UIImageView object
'name' shows URL parameter name.
NSString *str=#"http://xxx.xxx.xxx.xx/xxxx/xxxxx/xxxxx.php?action=add_place";
NSString *urlString = [NSString stringWithFormat:#"%#",str];
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"];
NSData *imageData = UIImageJPEGRepresentation(_showPhoto.image, 90);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"host_pic\"; filename=\"parkN.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter username
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userID\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"17" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter token
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"longitude\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"50.0011" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter token
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"latitude\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"50.0011" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"place_name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"lahore" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"place_description\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"lahore" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"zip_code\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"123456" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"phone_number\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"033333333" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"%#",dict);
If you want to name the image:
NSMutableString *nombreImagen= [[NSMutableString alloc]init];
[nombreImagen appendString:#"Content-Disposition: attachment; name=\"file\"; filename=\""];
[nombreImagen appendString:#"hoy"];
[nombreImagen appendString:#".jpg\"\r\n"];
.......
[body appendData:[[NSString stringWithString:nombreImagen] dataUsingEncoding:NSUTF8StringEncoding]];