first of all I am sorry for this kind of questions, I am a little confused with Objective C,
the function I am trying to write is to upload image to a server using web service, I have already dine it using C# but it I cann't figuir out what is the problem in my objective-C code
the C# code is:
using(var wb=new WebClient){
var Data=new NameValueCollection();
data["image"]=base64(fileName)/*base64 is a function to convert the image with"file name" to base64 string*/
Uri myUri=new Uri("http://localHost:8080/test2/sss/users/1/uploadImage");
var respose=wb.UploadValues(myUri,"Post",Data)
}
the Objective-C code I am trying to use:
NSData* data = UIImageJPEGRepresentation(theImageView.image, 1.0f);
[Base64 initialize];
NSString *strEncoded = [Base64 encode:data];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:#"http://localHost:8080/test2/sss/users/1/uploadImage"]];
NSData* image= [strEncoded dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES ];
NSLog(#"%#",strEncoded);
[request setHTTPBody:image];
(void)[NSURLConnection connectionWithRequest:request delegate:self];
sorry again but the problem is that I don't Know if I am matching the parameters right
You don't have to base64 encode the date, but use the right content type for your request. I didn't understand your problem, but here is my working method:
- (NSURLConnection *)connectionByFormUploadingData:(NSData *)data toURL:(NSURL *)url withFileName:(NSString *)fileName forFieldName:(NSString *)fieldName delegate:(id)delegate {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *boundary = [[NSProcessInfo processInfo] globallyUniqueString];
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField:#"Content-Type"];
NSMutableData *postData = [[NSMutableData alloc] initWithData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n\r\n", fieldName, fileName ?: #"empty_file_name"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:data];
[postData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postData];
return [[NSURLConnection alloc] initWithRequest:request delegate:delegate startImmediately:NO];
}
EDIT
Assumed you use PHP, you save the data like this:
move_uploaded_file($_FILES['fieldName']['tmp_name'], $upload_dir.'/'.$_FILES['fieldName']['name']);
EDIT II
The last boundary in the HTTP body must be terminated using two hyphens as described in RFC1341, thanks to CouchDeveloper for this improvement!
Try encoding your data a bit differently:
[strEncoded dataUsingEncoding:NSUTF8StringEncoding]
Related
In my iOS app I am posting json string to server using NSURLConnection like this.
post_string = #"{"function":"getHuddleDetails", "parameters": {"user_id": "167","location_id": "71","huddle_id": "328","checkin_id": "1287"},"token":""}"
-(void)myServerRequests:(NSString *)post_string{
NSData *postData = [post_string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.myServerURl.com/jsonpost"]];
[request setTimeoutInterval:100];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
webData = [[NSMutableData alloc]init];
}
}
And posting multipart/form-data (not JSON) using NSURLSession using below code
-(void)myFunction:(NSString *)user_name paswd:(NSString *)pass_word {
NSString *boundary = [self boundaryString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.myServerURl.com/formpost"]];
[request setHTTPMethod:#"POST"];
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary] forHTTPHeaderField:#"Content-Type"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"username\"\r\n\r\n%#", user_name] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"password\"\r\n\r\n%#", pass_word] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:postbody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSAssert(!error, #"%s: uploadTaskWithRequest error: %#", __FUNCTION__, error);
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
}];
[task resume];
}
This works perfectly fine with NSURLSession, but when I tried to post json string (converted it to NSDATA and posted using NSURLSession), it is not working.
Why it happens ?
Thanks in advance
If you want to send JSON to a server you should set the content type accordingly to application/json and your content is actually just that: the JSON encoded preferably in UTF-8.
In your method myServerRequests: you set content type application/x-www-form-urlencoded - but you don't setup the corresponding content correctly. How to do this can be read here: URL-encoded form data. Additionally, specifying a charset parameter has no effect at all.
In case you want to send a string parameter for a application/x-www-form-urlencoded content type, you should also not use a lossy conversion. Instead use UTF-8. Note that NSStrings length returns the number of UTF-16 code points - which is not the same as the number of bytes of an UTF-8 encoded string.
Recap:
Don't use application/x-www-form-urlencoded content type. Instead:
Content-Type = application/json
Content-Length = <length in bytes of the UTF-8 encoded JSON>
When you fix these issues, the request should be OK.
When using a multipart/form-data request I strongly recommend to use a network library. Doing this by hand is too error prone and you would need to read at least 300 RFCs to know that you are doing it correctly ;)
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.
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 need to send a pic to a server via HTTP post, but I am getting a response from server saying that I used POST+GET. Any ideas what I did wrong? Here is my code.
- (void)sendMessagesWithImg
{
NSMutableData *body = [NSMutableData data];
UIImage *imgColor = [UIImage imageNamed:#"imgbar.png"];
UIImage * imageToPost = [[UIImage alloc] init];
imageToPost = [self convertImageToGrayScale:imgColor];
// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:imageData];
}
[imgView setImage:imageToPost];
[body appendData:imageData];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"URL"]];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
}
Server response
More than the maximum number of request parameters (GET plus POST) for
a single request ([512]) were detected.
You append the imageData for two times. Delete the second.
[body appendData:imageData];
In any case try also with this:
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
and read this post..you have to attach others parameters probably:
ios Upload Image and Text using HTTP POST
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]];