I want to make http form post using NSURLConnection in iOS. I have two form fields and one file upload option in an HTML form. When I am doing same thing using NSURLConnection I am not getting a response.
NSString *urlString = #"http://url/test.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"myphoto.png\"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:filedata];
[body appendData:[[NSString stringWithFormat:#"&s=YL4e6ouKirNDgCk0xV2HKixt&hw=141246514ytdjadh"] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"RETURNED:%#",returnString);
But when I use ASIHTTPRequest and write the following code it's working and I am getting a response.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://url/test.php"]];
[request setPostValue:#"YL4e6ouKirNDgCk0xV2HKixt&hw" forKey:#"ssf"];
[request setPostValue:#"141246514ytdjadh" forKey:#"sds"];
[request setData:filedata withFileName:#"myphoto.png" andContentType:#"image/jpeg" forKey:#"file"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"response:%#",response);
}
Can anyone tell me what I'm doing wrong with the NSURLConnection part?
You are not copying the example of that link. In that tutorial, the HTTPBody parameter is supposed to be an instance of NSData, not NSString.
[request setHTTPMethod:#"POST"];
NSString *myString = [NSString stringWithFormat:#"value1=test3&value2=test"];
[request setHTTPBody:[myString dataUsingEncoding:NSUTF8StringEncoding]];
I tried this code for uploading the image and its working. Added boundry.
NSString *urlString = #"URL";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\"Test.png\"\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]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
This is working fine for me.
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableURLRequest *req=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"http:///URL/iinsert.php"]];
NSString *myreqstr=#"name=abhii&address=knrr";
NSData *myreqdata=[NSData dataWithBytes:[myreqstr UTF8String] length:[myreqstr length]];
[req setHTTPMethod:#"POST"];
[ req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[ req setHTTPBody: myreqdata ];
//[req setValue:#"abhii" forHTTPHeaderField:#"name"];
//[req setValue:#"kar" forHTTPHeaderField:#"address"];
NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSLog(#"%#",data);
NSString *returnstring=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",returnstring);
// Do any additional setup after loading the view, typically from a nib.
}
Try this ....
NSURL *url = [NSURL URLWithString:#"URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *myRequestString =#"Request string";
NSLog(#"%#",myRequestString);
NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
[ request setHTTPBody: myRequestData ];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
You have several
rn
in the end of your strings. All of them should be
\r\n
More precisely it should be:
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"myphoto.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
Related
I am a newbie to Objective-C and please let me elaborate what I am doing...
I am trying to upload a file to OneDrive using PUT request.
PUT request must contain
Http Headers
One Drive Documentation
content-length 7919
content-range bytes 0-7918/7919
and with these headers a file will be uploaded
PUT https://sn3302.up.1drv.com/up/fe6987415ace7X4e1eF866337
Content-Length: 7919
Content-Range: bytes 0-7918/7919
<bytes 0-7918 of the file>
Given below are the screen shots of whole PUT request using Chrome POSTMAN
I am trying to make a PUT request with given below headers:
and a file
Could you please guide me how can I do the above using Objective-C
PROBLEM
Everything is working fine with POSTMAN but when I am trying to do it with Objective-C, the file is not getting uploaded and I am getting the given below result:
{"error":{"code":"invalidRequest","message":"Declared fragment length
does not match the provided number of bytes"}}
Objective C code
-(void)uploadFile:(NSString*)uploadUrl
{
NSString *urlString = uploadUrl;
NSData* file = [NSData dataWithContentsOfFile: [#"/Users/username/Desktop/s.sql" stringByExpandingTildeInPath]];
NSString* fileName = #"s.sql";
//
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"PUT"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:#"7919" forHTTPHeaderField: #"Content-Length"];
[request addValue:#"bytes 0-7918/7919" forHTTPHeaderField: #"Content-Range"];
NSMutableData *putData = [NSMutableData data];
[putData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Append the file
[putData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[putData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%#\"\r\n", fileName]dataUsingEncoding:NSUTF8StringEncoding]];
[putData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[putData appendData:[NSData dataWithData:file]];
// Close
[putData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Append
[request setHTTPBody:putData];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
}
Thanks to God Finally I found a way. Given below is the edited and working code:
-(void)uploadFile:(NSString*)uploadUrl
{
NSString *urlString = uploadUrl;
NSData* file = [NSData dataWithContentsOfFile: [#"/Users/username/Desktop/s.sql" stringByExpandingTildeInPath]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"PUT"];
[request addValue:#"7919" forHTTPHeaderField: #"Content-Length"];
[request addValue:#"bytes 0-7918/7919" forHTTPHeaderField: #"Content-Range"];
NSMutableData *putData = [NSMutableData data];
[putData appendData:[NSData dataWithData:file]];
// Append
[request setHTTPBody:putData];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(resSrt);
}
I want to upload a image from phone to web service my link is like below as sample
"http://sample.com/upload_image.php"
my code is as below for post:
-(IBAction) post:(id) sender
{
count = 0;
self.progress = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
self.progress.center = self.view.center;
progress.hidden = NO;
[self.view addSubview:self.progress];
nmyTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateUI:) userInfo:nil repeats:YES];
NSString *filename = [NSString alloc];
filename = [self randomStringWithLength:5];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 100);
NSError *error;
NSData *searchData;
NSHTTPURLResponse *response;
// setting up the URL to post to
NSString *urlString = #"http://dev9.edisbest.com/upload_image.php";
// 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:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n",filename] 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]];
// setting the body of the post to the reqeust
searchData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",response);
NSString *imageName;
imageName = [[NSString alloc] initWithData:searchData encoding:NSUTF8StringEncoding];
NSLog(#"retrun Result of Upload Photo.. %#",imageName);
[request setHTTPBody:body];
// now lets make the connection to the web
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{ NSLog(#"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]); }];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
///self.returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",returnString);
}
when i build and run i will be asked to choose image and when i select an image to upload
I got a message as the following
**[Switching to process 553 thread 0x4e03]
2015-04-28 12:08:12.856 image-video-upload[553:207] (null)
2015-04-28 12:08:12.857 image-video-upload[553:207] retrun Result of Upload Photo..
2015-04-28 12:08:12.889 image-video-upload[553:207] Finished with status code: 0**
Above message shown in my console and crashed
Try this..
UIImage *image=[UIImage imageNamed:#"i3.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *encodedString = [imageData base64EncodedStringWithOptions:0];
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:encodedString forKey:#"imageData"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"http://Your url";
NSURL *url = [NSURL URLWithString:urlString];
// Prepare the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"json" forHTTPHeaderField:#"Data-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&theResponse
error:&errorReturned];
Here is the code from my project to upload image
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
We have a PHP web service that attaches an image to an email since it is collecting the image in a global file array. The method of transfer of the data is the POST method . I am sending the image but it is not getting collected in the web service with the POST method. Can someone tell me if the problem is in the web service or in my code.
Below is the code i am using to send the image.
NSString *tempString = [NSString stringWithFormat:#"sub1_fname=%#&sub1_lname=%#&sub1_email=%#&sub1_phone=%#&sub1_address=%#&sub1_city=%#&sub1_zip=%#&sub2_storage=%#&sub2_boxes=%#&sub2_oneman=%#&sub2_twoman=%#&sub2_heavy=%#&sub2_comments=%#&sub3_findus=%#&sub3_word=%#&sub3_praise=%#",f31fname,f31lname,f31email,f31phone,f31address,f31city,f31zip,f32storage,f32boxes,f32oneman,f32twoman,f32heavy,f32comments,f33findus,f33word,f33praise];
UIImage *image = [UIImage imageNamed:#"textlogo.png"];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://ommultiengg.com/form/form3.php"]];
[request setHTTPMethod:#"POST"];
NSString *postString =[NSString stringWithFormat:#"{\"sub2_image\":\"%#\"}",image];//post the image
[request setValue:[NSString
stringWithFormat:#"%lu", (unsigned long)[postString length]]
forHTTPHeaderField:#"Content-length"];//get image length
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[tempString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Using following code, you can pass parameters as well as with image data.
NSString *urlString = [NSString stringWithFormat:#"http://myAPIName/MethodName/test.php&username=%#&password=%#&image=%#&answer=%#&question_id=%#", username, password, imageName, answer, questionID];
NSLog(#"MyURL: %#",urlString);
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
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]];
NSString *str=[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"SourceImage\"; filename=\"Image_%#\"\r\n",[imagePath lastPathComponent]];
[body appendData:[[NSString stringWithString:str] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithContentsOfFile:imagePath]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
I am trying to upload a file like this:
- (NSString *)uploadWithTarget:(NSString *)url andFileData:(NSData *)file andMD5Checksum:(NSString *)checksum andFileName:(NSString *)name
{
uploadFinished = false;
NSString *response = #"";
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];
NSURL * urll = [NSURL URLWithString:url];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:urll];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest addValue:checksum forHTTPHeaderField:#"Md5Hash"];
[urlRequest addValue:#"Keep-Alive" forHTTPHeaderField:#"Connection"];
NSString *boundary = #"*****";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[urlRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"%#\"\r\n", name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/xml\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:file]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[urlRequest setHTTPBody:body];
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest];
//[dataTask resume];
NSURLSessionUploadTask *uploadTask = [defaultSession
uploadTaskWithRequest:urlRequest
fromData:file
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (!error && httpResp.statusCode == 200) {
NSLog(#"Request body %#", [[NSString alloc] initWithData:[urlRequest HTTPBody] encoding:NSUTF8StringEncoding]);
} else {
}
}];
[uploadTask resume];
return response;
}
But my Server always responds File not Found! Is that not correct code?!
- (void) uploadLog :(NSString *) filePath
{
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
NSString *urlString =[NSString stringWithFormat:#"http://www.yoursite.com/accept.php"];
// to use please use your real website link.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"_187934598797439873422234";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:#"User-Agent"];
[request setValue:#"http://google.com" forHTTPHeaderField:#"Origin"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"Content-Length %d\r\n\r\n", [data length] ] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"picture\"; filename=\"%#.png\"\r\n", #"newfile"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", [body length]] forHTTPHeaderField:#"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
And here is the php part that works for me.
<?php
$target_path = "./uploads/";
$target_path = $target_path . basename( $_FILES['picture']['name']);
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name'])." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
I've been trying for days on how to upload an image to an API. There is a cURL example there like this.
curl "http://address.com/api/" -F "parameter[name]=My Upload" -F "parameter[description]=this is my upload" -F "parameter[other]=additional info" -F "parameter[image]=#wake_2560x1600.jpg;type=image/jpg"
How would I use this to upload to a server via an NSMutableURLRequest & NSURLConnection? I have tried a few different ways but have not succeeded. Anyone have any ideas?
EDIT:
I'm currently trying out ASIFormDataRequest
NSData *imageData = UIImageJPEGRepresentation(image, 0.9);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request addRequestHeader:#"User-Agent" value:#"iOS App"];
[request addPostValue:#"name" forKey:#"parameter[name]"];
[request addPostValue:#"description" forKey:#"parameter[description]"];
[request addPostValue:#"other" forKey:#"parameter[other]"];
[request addData:imageData withFileName:[NSString stringWithFormat:#"jpeg_%d.jpg", rand()] andContentType:#"image/jpeg" forKey:#"param[image]"];
[request startAsynchronous];
Rough way of doing it.
PHP Script.
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
IOS code
- (void)upload:(UIImage *)image {
NSData *imageData = UIImageJPEGRepresentation(image, 80);
NSString *urlString = #"http://www.upload.com/upload.php"; // URL of upload script.
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:[#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.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]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"returnString: %#", returnString);
}
Just make sure the variable name you use is the same, in here i use "uploadedfile" both for php and ioscode
php
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
ios
[body appendData:[#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// although right now im using https://github.com/samvermette/SVHTTPRequest
if you import that library in your code then making upload would be as easy as this
[SVHTTPRequest POST:#"http://www.upload.com/upload.php"
parameters:[NSDictionary dictionaryWithObjectsAndKeys:imageData, #"uploadedfile", nil]
progress:^(float progress) {
progressLabel.text = [NSString stringWithFormat:#"Uploading (%.0f%%)", progress*100];
}
completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
progressLabel.text = #"Upload complete";
}];