Objective-C (Upload a Single Image to a Server) - ios

All,
I just want to upload a single screenshot from my App to a server directory. The screenshot code works good as I can send it via SMS in another routine and it compiles just fine, but I don't see the image in the server directory using the code below.
I just can't get it to work. I ONLY care to upload the screenshotimage variable...the rest of the data is not important to me. Please Help!!!
- (IBAction)sendToServer {
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshotimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImageJPEGRepresentation(screenshotimage,0.2);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://www.nameofmywebsite.com/temp/image_from_payer_app"]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"xxxxBoundaryStringxxxx";
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=\"iphoneimage.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];
[request addValue:[NSString stringWithFormat:#"%lu", (unsigned long)[imageData length]] forHTTPHeaderField:#"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
Here is my new code. I am only trying to send a single image file (which is a screenshot of the app) to a server. Can someone please verify that the client code is correct then I can just focus on the server side to see why the file is not being deposited on the server?
- (IBAction)sendToServer {
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshotimage = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(screenshotimage,0.2);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://mywebsite.com/"]];
[request setHTTPMethod:#"POST"];
appendData:[NSData dataWithData:imageData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
UIGraphicsEndImageContext();
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
}

Your client side code is seems ok. There might be some problem at your server side. Your server might unable to retrieve the image.

Related

upload image to web service from database using xcode

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];

how to upload multiple images to server ios?

I am trying to upload Image From my IOS device to server. when upload single image file to server it is successfully uploaded to my server. i want to upload multiple image files to server how can i do this.
// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:#"icon.png"], 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
NSString *filename = #"icon";
// Create 'POST' MutableRequest with Data and Other Image Attachment.
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 *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
Muliple images upload attempted code
-(void)uploadImageToServer:(NSArray*)arrUploadData withTreatmentDetails:(NSDictionary *)dictArguments url:(NSString*)url
{
// COnvert Image to NSData
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
// Create 'POST' MutableRequest with Data and Other Image Attachment.
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 *postbody = [NSMutableData data];
for (int i=0; i<[arrUploadData count]; i++)
{
NSData *dataImage = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyData"];
NSString *filename = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyimagename"];
if (dataImage)
{
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
}
Hello, You can do it by using NSMutableArray
For Example :
NSMutableArray *arrayImageData = [[NSMutableArray alloc]init];
Take images from imagepicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
NSString *filePath,*path;
NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
[arrayImageData addObject:dataImage];
filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"screenShot1.png"];
[picker dismissViewControllerAnimated:YES completion:nil];
}
At the time of posting image on Server use following code
for (int i = 0; i < [arrayImageData count]; i++)
{
[request setPostValue:[[MYUtility getInstance] base64StringFromNSData:[arrayImageData objectAtIndex:i]] forKey:[NSString stringWithFormat:#"Image%d", i + 1]];
}
Hope this will help for you...I used this code for saving multiple images on server.

Image is not getting sent to the PHP web service through POST method in IOS

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];

iOS Photo Upload to a server

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";
}];

Form Data Request using NSURLConnection in iOS

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]];

Resources