Issue with large size images in HTTP Post - ios

See my code which i used to post image in Web server. I can send small size image. but its not working for the large size images. Where i should modify this code to enable large size images
NSString *requestString =[NSString stringWithFormat:#"UserId=%#&CategoryId=%#&Continent=%#&Country=%#&City=%#&Gender=%#&ImageName=%#&AgeRange=%#",UserId,CategoryId,continentTextfield.text,countrytextfield.text,citytextfield.text,gender,imagename,ageTextfield.text];
NSString *url=[NSString stringWithFormat:#"http://192.168.2.4:98/UserImage.svc/InsertFacialImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImagePNGRepresentation(chosenImage);
// NSData *data = [NSData dataWithData:UIImagePNGRepresentation(chosenImage)];
[request addValue:#"image/png" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq)
{
NSLog(#"Connection Sucessful");
}
else {
NSLog(#"failed");
}
[connReq start];

CGFloat compr = 0.9f; //comress the size of the image
CGFloat maxCompre = 0.1f; //max allowed compression from 0 to 1
int maxSize = 250*1024; //max file size
NSData *imageData = UIImageJPEGRepresentation(yourImage, compr);
while ([imageData length] > maxSize && compr > maxCompre)
{
compr -= 0.1;
imageData = UIImageJPEGRepresentation(yourImage, compression); //compress the size
}
finally u pass the imageData to the server

Related

How do I convert this curl command to Objective-C

the command:
curl -X POST -F "search={\"page\":\"1\",\"county\":\"18\",\"type\":\"J\"} " -H "Host: 118932.ro" http://118932.ro/dezv/ipa/index.php
This is what I have so far:
url = [NSURL URLWithString:#"http://www.118932.ro/dezv/ipa/index.php"];
NSData *data = [NSJSONSerialization dataWithJSONObject:self.requestData options:0 error:&error];
NSString *bodyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *dataString = [NSString stringWithFormat:#"\"search=%#\"",bodyString];
NSData *dataBody = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:dataBody];
[request setValue:#"118932.ro" forHTTPHeaderField:#"Host"];
where self.requestData is the following dictionary
self.requestData = #{#"page" : #"1", #"county" : #"18", #"type" : #"J"};
but this doesnt seem to give me any results after I do this
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
Here is the code I use. The -F parameter in cUrl specifies the actual post data, so you may want to use the string "search={\"page\":\"1\",\"county\":\"18\",\"type\":\"J\"} " as is. You should call this code in a background thread as the synchronous call will block the UI.
/**
* Do an HTTP POST request and return the results
*
* #param NSString * url the URL
* #param NSString * post the POST data
*
* #return NSDictionary * a dictionary containing the response, error, and data
*/
+ (NSDictionary *)httpPostRequestWithUrl:(NSString *)url post:(NSString *)post
{
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", (int)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:30]; // set timeout for 30 seconds
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSMutableDictionary *rc = [[NSMutableDictionary alloc] init];
if ( response )
[rc setObject:response forKey:#"response"];
if ( error )
[rc setObject:error forKey:#"error"];
if ( data )
[rc setObject:data forKey:#"data"];
return (NSDictionary *)rc;
}

NSURLSession for sending multiple images by multiple urls

The below code i am using for sending multiple images along with the text. but only one image is saving in Web server. Here the problem is i need to get response from the first url and i've to assign it to the second url.
NSLog(#"PassedID%#",PassedUserId);
NSLog(#"integer=%#", [[NSUserDefaults standardUserDefaults] objectForKey:#"Person"]);
NSString *CategoryId=#"3";
NSString *imagename=#"ComparisonObject";
NSString *requestString =[NSString stringWithFormat:#"UserId=%#&CategoryId=%#&Continent=%#&Country=%#&City=%#&Gender=%#&ImageName=%#",PassedUserId,CategoryId,continentTextfield.text,countrytextfield.text,citytextfield.text,GenderText.text,imagename];
NSLog(#"%#",requestString);
NSString *url=[NSString stringWithFormat:#"http://192.168.2.4:98/UserImage.svc/InsertObjectImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *uploadImage1 = [session dataTaskWithRequest:request completionHandler:^(NSData *data2, NSURLResponse *response, NSError *error) {
// Finish uploading image 1
// Get response and data to prepare to update image 2
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage1, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"recievedData%#",receivedData);
NSString *imagename=#"ComparisonObject";
NSString *requestString1 =[NSString stringWithFormat:#"UserId=%#&ImageId=%#&=ImageName%#",PassedUserId,compareId,imagename];
NSLog(#"%#",requestString1);
NSString *url=[NSString stringWithFormat:#"http://192.168.2.4:98/UserImage.svc/UpdateObjectImage?%#",requestString1];
NSMutableURLRequest *request2 = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSURLSessionDataTask *uploadImage2 = [session dataTaskWithRequest:request2 completionHandler:^(NSData *data1, NSURLResponse *response, NSError *error) {
NSLog(#"recievedData%#",receivedData);
NSString *imagename=#"ComparisonObject";
NSString *requestString1 =[NSString stringWithFormat:#"UserId=%#&ImageId=%#&=ImageName%#",PassedUserId,compareId,imagename];
NSLog(#"%#",requestString1);
NSString *url=[NSString stringWithFormat:#"http://192.168.2.4:98/UserImage.svc/UpdateObjectImage?%#",requestString1];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage2, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
// Finish uploading image 2
}];
}];

Post Two images to Web server

Below code i wrote for sending two images. But i failed to find the code why its not working. i am new to iOS and even stackoverflow. Still am thinking the code is ok. just help me to find my mistake. how i modify the code to able to send two images with different services(each service have a separate url).
NSString *requestString =[NSString stringWithFormat:#"requestUserId=%#&CategoryId=%#&Continent=%#&Country=%#&City=%#&Gender=%#&ImageName=%#&AgeRange=%#",userID,CategoryId1,continentTextfield.text,countrytextfield.text,citytextfield.text,GenderText.text,imagename,ageTextfield.text];
NSLog(#"request%#",requestString);
NSString *url=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/InsertObjectImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Status code: %d", [response statusCode]);
NSLog(#"respdata%#",respData);
if ([response statusCode]==200)
{
self.userId=[[NSUserDefaults standardUserDefaults]objectForKey:#"Sendd"];
NSLog(#"recievedData%#",receivedData);
NSString *requestString1 =[NSString stringWithFormat:#"requestUserId=%#&ImageId=%#&=ImageName%#",userID,compareId,imagename];
NSLog(#"%#",requestString1);
NSString *url1=[NSString stringWithFormat:#" http://37.187.152.236/UserImage.svc/UpdateObjectImage?%#",requestString1];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] init] ;
[request1 setURL:[NSURL URLWithString:url1]];
[request1 setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request1 setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request1 addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body1 = [NSMutableData data];
[body1 appendData:[NSData dataWithData:data]];
[request setHTTPBody:body1];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Status code: %d", [response statusCode]);
NSLog(#"respdata%#",respData);
homeViewController *homVew =[[homeViewController alloc]initWithNibName:#"homeViewController" bundle:nil];
self.navigationItem.hidesBackButton = YES;
[self.navigationController pushViewController:homVew animated:YES];
}

Post multiple images into web server

The code make me very happy to Post image into Web server. its working smart for single image. The code what i've to used to Post a single image is
NSLog(#"%#",requestString);
NSString *url=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/InsertFacialImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
Then i failed to jump over the hurdle, Failed to Post 2 images with different services.The truth behind my failure is after uploading of the 1st image, server generate response then i've attach the response to second service. i did it properly but failed because i made the connection run 2 times for 2 images.but Web services team asking me that run it in a single connection.The code which i is used, which i need to modify is
Posting 1st image
NSString *url=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/InsertObjectImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage1, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Status code: %ld", (long)[response statusCode]);
Generating Response
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"%#" , error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError *e;
jsonDict1 = [NSJSONSerialization JSONObjectWithData:receivedData options: NSJSONReadingMutableContainers error: &e];
compareId = [jsonDict1 valueForKey:#"ImageId"];
NSLog(#"JSONN%#" , jsonDict1);
compareId = [results.firstObject objectForKey:#"ImageId"];
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:self.compareId forKey:#"Sendy"];
[defaults synchronize];
NSLog(#"compareId:%#",compareId);
results = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:&e];
}
}
after this step is response is generating good and i can pass it to the second string. so no problem with the server response.
*Post 2nd Image *
NSString *url1=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/UpdateObjectImage?%#",requestString1];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] init] ;
[request1 setURL:[NSURL URLWithString:url1]];
[request1 setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request1 setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage2, 0.2f);
[request1 addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body1 = [NSMutableData data];
[body1 appendData:[NSData dataWithData:data]];
[request1 setHTTPBody:body1];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request1 delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
NSLog(#"Status code: %ld", (long)[response statusCode]);

Uploading an image and some other parameters in single post request

I am trying to upload an image along with some text. I am able to POST the text but somehow the image doesn't reach to server.
Following is my code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *password = [[Utilities sharedConfiguration] sha1:txtPassword.text];
NSString *post = [NSString stringWithFormat:#"id_sender=%#&token=%#&array_receiver=%#&message=%#&time_allowed=%#&password=%#",[defaults objectForKey:#"id_user"],[defaults objectForKey:#"token"],selectedContact,txtMessage.text,txtTime.text,password];
NSLog(#"post %#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableData *data = [NSMutableData dataWithData:postData];
//NSMutableData *data = nil;
if(myimage!=nil){
NSString *boundary = #"---------------------------14737809831466499882746641449";
[data appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filetype=\"image/png\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:#"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[NSData dataWithData:UIImagePNGRepresentation(myimage)]];
}
NSString *postLength = [NSString stringWithFormat:#"%d", [data length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://www.myurl.com/send_message_17294.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
[MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
[NSURLConnection connectionWithRequest:request delegate:self];
You can use AFNetworking so you don't have to digg into the multi-part request format.
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://hostport"]];
NSDictionary *simpleParams = #{ #"key": #"value" };
NSMutableURLRequest* request = [client multipartFormRequestWithMethod:#"POST" path:#"/path" parameters: simpleParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:fileData
name:#"paramName"
fileName:#"filename.png"
mimeType:#"image/png"];
}];
Then create an operation depending on the expected response. For example if you expect JSON:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// handle success
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// handle error
}];
You can get more information in the AFNetworking documentation.
Try this : Its a Synchronous Request. And image is in base64 string format
NSString * param = [NSString stringWithFormat:#"%#=%#&%#=%#&%#=%#",
#"uphoto",imageData, #"category",categoryName, #"name",FIRSTNAME]; // parameters
NSData *postData = [param dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://www. ..."];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[req setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *res = nil;
NSData *responceData = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&error];
if (error)
{
//handle error
return nil;
}
else
{
}

Resources