post image and test using multipart, but it gave me error Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request ,i am not able to post please help
thanks in advance
NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init];
[post_dict setObject:Name.text forKey:#"name"];
[post_dict setObject:ContactNameTF.text forKey:#"contactname"];
[post_dict setObject:EmailTf.text forKey:#"email"];
[post_dict setObject:PasswordTF.text forKey:#"password"];
[post_dict setObject:HouseNumberTF.text forKey:#"housenumber"];
[post_dict setObject:StreetTF.text forKey:#"street"];
[post_dict setObject:cityTF.text forKey:#"city"];
[post_dict setObject:POstcodeTF.text forKey:#"postalcode"];
[post_dict setObject:ContactNumberTF.text forKey:#"contact"];
//[post_dict setObject:self.theImage forKey:#"image_url"];
NSString *urlString = #"http://www.ofertas24.net/codegen/index.php/codegen/register_post";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// add the image form fields
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image_url\"; filename=\"%#image.jpg\"\r\n",NameTF.text ] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:self.theImage];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// add the text form fields
for (id key in post_dict) {
NSLog(#"%#",key);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[post_dict objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
// close the form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
// send the request (submit the form) and get the response
NSOperationQueue *queue =[[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if ([result isEqualToString:#"true"]) {
[self performSelectorOnMainThread:#selector(mainViewController) withObject:nil waitUntilDone:NO];
}
else {
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
try this code,hope it helps you. . . . . . .. . . . . ..
NSString *baseurl = #"Enter URL here";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Set Params
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
//Create boundary, it can be anything
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
//Populate a dictionary with all the regular values you would like to send.
NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init];
[post_dict setObject:Name.text forKey:#"name"];
[post_dict setObject:ContactNameTF.text forKey:#"contactname"];
[post_dict setObject:EmailTf.text forKey:#"email"];
[post_dict setObject:PasswordTF.text forKey:#"password"];
[post_dict setObject:HouseNumberTF.text forKey:#"housenumber"];
[post_dict setObject:StreetTF.text forKey:#"street"];
[post_dict setObject:cityTF.text forKey:#"city"];
[post_dict setObject:POstcodeTF.text forKey:#"postalcode"];
[post_dict setObject:ContactNumberTF.text forKey:#"contact"];
[post_dict setObject:self.theImage forKey:#"image_url"];
// add params (all params are strings)
for (NSString *param in post_dict) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [post_dict objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSString *FileParamConstant = #"Enter Key Of Image Paramater";
NSData *imageData = UIImageJPEGRepresentation(image, 1);
//Assuming data is not nil we add this to the multipart form
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the request
[request setHTTPBody:body];
// set URL
[request setURL:[NSURL URLWithString:baseurl]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if ([result isEqualToString:#"true"]) {
[self performSelectorOnMainThread:#selector(mainViewController) withObject:nil waitUntilDone:NO];
}
else {
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
Related
I am trying to POST multiple images to the server but only one image is going to the server. I am trying to save multiple images. My code is below plz tell me where I am wrong. I have seen this example of posting multiple images.
Upload multiple images in one request
Thanks
NSData *imageData1 = UIImageJPEGRepresentation(photo1, 0.8);
NSData *imageData2 = UIImageJPEGRepresentation(photo2, 0.8);
NSData *imageData3 = UIImageJPEGRepresentation(photo3, 0.8);
NSData *imageData4 = UIImageJPEGRepresentation(image1, 0.8);
NSData *imageData5 = UIImageJPEGRepresentation(image2, 0.8);
NSString *returnString;
NSDictionary *aParametersDic= #{#"input_100":userIDStr,#"input_1":regstrationNumberStr,#"input_88":regsDateStr,#"input_2":nameofHealthSeekerString,#"input_83":ageString1,#"input_84":weightStr,#"input_85":heightStr,#"input_3":motherNameStr,#"input_4":addressStr,#"input_5":phonenumberStr,#"input_95":alternativeNumberStr,#"input_6":emailStr,#"input_7":whatsAppStr,#"input_96":idProofStr1,#"input_8":professionStr1,#"input_9":maritialStatusStr,#"input_11":presentHistoryStr,#"input_12":pastHistoryStr,#"input_13":familyHistoryStr,#"input_15":sleepStr,#"input_16":freshStatusStr,#"input_17":sleepPillsStr,#"input_20":DietStr,#"input_21":spiceStr,#"input_23":apetiteStr,#"input_25":foodChewingHabbit,#"input_27":breakfastItemStr,#"input_29":lunchItemStr,#"input_31":eveningItemStr,#"input_33":dinnerItemStr,#"input_94":mentalStatus,#"input_36":relationStr,#"input_38":constipationStr,#"input_39":urinaryStr,#"input_41":habitStr,#"input_45":tasteOfMouthStr,#"input_47":sexualStr,#"input_49":fatiqueStr,#"input_51":regularExerciseStr,#"input_53":workingHoursStr,#"input_55":favDishStr,#"input_57":otherDetailsStr,#"input_59":femalStatsStr,#"input_60":progressReportStr,#"input_77":referredByStr,#"input_75_1":hearAboutStr,#"input_78":willingStr,#"input_87":_mentorNameTextField.text,#"input_90":_phonenumberTextField.text,#"input_91":_addressTextField.text};
// It's contains other parameters.
NSDictionary *aImageDic = #{#"input_93":imageData1,#"input_98":imageData2,#"input_92":imageData3,#"input_82":imageData4,#"input_97":imageData5 }; // It's contains multiple image data as value and a image name as key
NSString *urlString = [NSString stringWithFormat:#"http://nse/apis/custom/?api=1&page=user_patient_form"]; // an url where the request to be posted
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] initWithURL:url] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831e45466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
NSString *postData = [self getHTTPBodyParamsFromDictionary:aParametersDic boundary:boundary];
[postbody appendData:[postData dataUsingEncoding:NSUTF8StringEncoding]];
[aImageDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if(obj != nil)
{
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"PostedImage\"; filetype=\"image/png\"; filename=\"%#\"\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:obj]];
}
}];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
if([[jsonDict objectForKey:#"status"]boolValue])
{
NSLog(#"data saved successfully");
}
else
{
NSLog(#"Error in saving the data");
}
});
When PHP response is
Printing description of returnString:
Array
(
[PostedImage] => Array
(
[name] => input_82
[type] => image/jpeg
[tmp_name] => /tmp/phpIfld44
[error] => 0
[size] => 225219
)
)
Try this one.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:#"IOS Testing" forKey:#"subject"];
[parameters setValue:#"Message" forKey:#"message"];
for (NSString *param in parameters) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSMutableArray *multipleArray=[[NSMutableArray alloc] init];
[multipleArray addObject:[UIImage imageNamed:#"images.jpeg"]];
[multipleArray addObject:[UIImage imageNamed:#"pic3.png"]];
for (int i=0; i<multipleArray.count;i++ )
{
NSData *imageData;
imageData = UIImageJPEGRepresentation([multipleArray objectAtIndex:i], 1.0);
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", #"uploaded_file[]"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setURL:[NSURL URLWithString:BASEURL]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse =
(NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200) {
NSLog(#"success");
}
}];
}
Your can use this code. It's tested and I am using this methods to upload multiple images along with other parameters.
if([arrImage count])
{
for (int y = 0; y < [arrImage count]; y++)
{
//-- Convert string into URL
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:UPLOADDATA_URL]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//-- Append data into posr url using following method
NSMutableData *body = [NSMutableData data];
//Project ID
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",#"project_id"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",projectId] dataUsingEncoding:NSUTF8StringEncoding]];
//Date
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",#"date"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",dateString] dataUsingEncoding:NSUTF8StringEncoding]];
//User ID
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",#"user_id"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",userID] dataUsingEncoding:NSUTF8StringEncoding]];
//Comment
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",#"comment"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",projectNoteTextView.text] dataUsingEncoding:NSUTF8StringEncoding]];
//Task ID
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",#"task_assign_id"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",task_Id] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
image_name =[NSString stringWithFormat:#"%#%d",#"image",y];
NSLog(#"IMAGE NAME:%#", image_name);
UIImage* imageFile = [arrImage objectAtIndex:y];
CGSize newSize = CGSizeMake(500.0f, 500.0f);
UIGraphicsBeginImageContext(newSize);
[imageFile drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// NSData *dataImg = [NSData dataWithData:UIImagePNGRepresentation(newImage)]; //compressed Imge
// NSData *dataImg = [NSData dataWithData:UIImagePNGRepresentation([arrImage objectAtIndex:y])];
NSLog(#"Images, send to server:%#", dataImg);
NSLog(#"added %i", y+1);
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"site_image\"; filename=\"%#\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:dataImg]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//-- Sending data into server through URL
[request setHTTPBody:body];
//-- Getting response form server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
}
[self showAlertMessage:[result objectForKey:#"message"]];
}
This is my web service call. if i am calling web services continuously, after some time start getting time out error, but internet is available.
Same web services working properly in android
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
request.timeoutInterval = 30;
request.URL = [NSURL URLWithString:finalURL];
request.HTTPMethod = #"POST";
[request setValue:#"123456" forHTTPHeaderField:#"header"];
if (parameters != nil) {
NSMutableData * body = [[NSMutableData alloc] init];
NSString *boundary = #"---------------------------V2ymHFg03ehbqgZCaKO6jy";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
for (id key in parameters) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#", [parameters objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
}
[request addValue:[NSString stringWithFormat:#"%lu", (unsigned long)[body length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:body];
}
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
// This will get the NSURLResponse into NSHTTPURLResponse format
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if (httpResponse.statusCode == 200) {
NSMutableDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog( #"Response = %#",JSON);
});
} else {
NSLog( #"Error = %#",error);
}
}];
It seems like you are accessing wrong array.
for (id key in parameters) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#", [parameters objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
}
parameters in above code seems to be an string array instead of dictionary.
You can use below code instead.
[parameters enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj,BOOL *_Nonnull stop) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#", obj] dataUsingEncoding:NSUTF8StringEncoding]];
}];
Try this:
NSString *strServicePath = #"YourURLString";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:strServicePath]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithFormat:#"Boundary-%#", [[NSUUID UUID] UUIDString]];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSDictionary *_params = [NSDictionary dictionaryWithObjectsAndKeys:yourValue,#"yourKey",nil];
// post body
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
for (NSString *param in _params) {
NSMutableString *strPart = [NSMutableString stringWithFormat:#"%#",[self createPartWithKey:param value:[_params objectForKey:param] boundary:boundary encoding:#"8bit" contentType:#"text/plain" contentFilename:#""]];
[body appendData:[strPart dataUsingEncoding:NSUTF8StringEncoding]];
}
//You can give your own strProfileImageName
NSString *strProfileImageName = [NSString stringWithFormat:#"%#_%#_.jpg",#"some_pic",_userID];
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#; filename=%#\r\n", #"some_pic",strProfileImageName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request queue: [NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//Your Code Here
}];
Try to implement in this. Hope this helps.
I want to upload more than one image in single service request. How can I do that. As of now I am able to upload single image like as
NSData *imageData = UIImageJPEGRepresentation(image, 90);
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableData *postBody = [NSMutableData data];
// file
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"files\"; filename=\”%#\”\r\n”,#“imagename”]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
Now I want to upload two images to server how can I do that.
Your answer is here. It's tested and I am using this below methods to upload multiple image along with other parameters.
- (void)uploadMultipleImageInSingleRequest
{
NSString *returnString;
NSDictionary *aParametersDic; // It's contains other parameters.
NSDictionary *aImageDic; // It's contains multiple image data as value and a image name as key
NSString *urlString; // an url where the request to be posted
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] initWithURL:url] ;
[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];
NSString *postData = [self getHTTPBodyParamsFromDictionary:aParametersDic boundary:boundary];
[postbody appendData:[postData dataUsingEncoding:NSUTF8StringEncoding]];
[aImageDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if(obj != nil)
{
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"PostedImage\"; filetype=\"image/png\"; filename=\"%#\"\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:obj]];
}
}];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
}
.
-(NSString *) getHTTPBodyParamsFromDictionary: (NSDictionary *)params boundary:(NSString *)boundary
{
NSMutableString *tempVal = [[NSMutableString alloc] init];
for(NSString * key in params)
{
[tempVal appendFormat:#"\r\n--%#\r\n", boundary];
[tempVal appendFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n%#",key,[params objectForKey:key]];
}
return [tempVal description];
}
One option use AFNetworking to upload multiple images
//create image data
UIImage *image = ......
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
UIImage *image2 = ......
NSData *imageData2 = UIImageJPEGRepresentation(image2, 0.5);
//Now add to array and also create array of images data
NSArray *arrImagesData = [NSArray arrayWithObjects:imageData,imageData2,nil];
//Create manager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//parameters if any
NSDictionary *parameters = .......
//Now post
[manager POST:#"your url here" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//add img data one by one
for(int i=0; i<[arrImagesData count];i++)
{
NSData *imageData = arrImagesData[i];
NSString *strName = [NSString stringWithFormat:#"name%d",i]
[formData appendPartWithFormData:imageData name:strName];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:#"IOS Testing" forKey:#"subject"];
[parameters setValue:#"Message" forKey:#"message"];
for (NSString *param in parameters) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSMutableArray *multipleArray=[[NSMutableArray alloc] init];
[multipleArray addObject:[UIImage imageNamed:#"images.jpeg"]];
[multipleArray addObject:[UIImage imageNamed:#"pic3.png"]];
for (int i=0; i<multipleArray.count;i++ )
{
NSData *imageData;
imageData = UIImageJPEGRepresentation([multipleArray objectAtIndex:i], 1.0);
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", #"uploaded_file[]"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setURL:[NSURL URLWithString:BASEURL]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200) {
NSLog(#"success");
}
}];
}
#define kStartTag #"--%#\r\n"
#define kEndTag #"\r\n"
#define kContent #"Content-Disposition: form-data; name=\"%#\"\r\n\r\n"
#define kBoundary #"---------------------------14737809831466499882746641449"
-(void)uploadImageonServers
{
NSMutableURLRequest *request = nil;
NSLog(#"image upload");
NSMutableData *body = [NSMutableData data];
request = [[NSMutableURLRequest alloc] init];
NSString *requestURL = [NSString stringWithFormat:#"http://192.168.1.101/gmento/index.php/api/professional/addServices"];
[request setURL:[NSURL URLWithString:requestURL]];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",kBoundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
// user ID parameter
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kContent, #"professional_id"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"1232" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
// Grop ID parameter
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kContent, #"title"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"test" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
// prepration_type_id parameter
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kContent, #"price"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"test" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
// description parameter
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kContent, #"description"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"test" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableArray *arr_images=[[NSMutableArray alloc] init];
[arr_images addObject:[UIImage imageNamed:#"1.jpg"]];
[arr_images addObject:[UIImage imageNamed:#"1.jpg"]];
for (int i=0; i<arr_images.count;i++ )
{
NSData *image_videoData;//isImageSet?imgMyProfPict.image:#""
image_videoData = UIImageJPEGRepresentation([arr_images objectAtIndex:i], 1.0);
if (image_videoData)
{
// image File
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#; filename=imageName.jpeg\r\n", #"services_image[]"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:image_videoData];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
for (int i=0; i<arr_images.count;i++ )
{
NSData *image_videoData;//isImageSet?imgMyProfPict.image:#""
image_videoData = UIImageJPEGRepresentation([arr_images objectAtIndex:i], 1.0);
if (image_videoData)
{
// image File
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#; filename=imageName.jpeg\r\n", #"glimpses_image[]"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:image_videoData];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error;
id receivedData = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dicResponse = (NSDictionary *)receivedData;
if ([[dicResponse valueForKeyPath:#"status"] intValue] == 1)
{
}
else
{
}
}
I am doing small project in which I need to send image file to server for that I am using multipart request.
following is my code
UIImage *resizedImage1 = [img resizedImage:CGSizeMake(90.0f, 90.0f) interpolationQuality:kCGInterpolationHigh];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(resizedImage1,0.8)];
NSString *urlString = #"myUrl/accounts/add_profile_image";
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];
// NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; image/jpeg; boundary=%#",boundary];
NSString *accessToken=[[NSUserDefaults standardUserDefaults]objectForKey:#"userAccesstoken"];
NSLog(#"access token %#",accessToken);
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:accessToken forHTTPHeaderField:#"auth"];
NSLog(#"request has %#",request);
// NSLog(#"imagedata has %#",imageData);
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// parameter v=1000
[postbody appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"v\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"1000\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
// mz_access_token sewt token parameter
[postbody appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"mz_access_token\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"%#\r\n",accessToken]dataUsingEncoding:NSUTF8StringEncoding]];
// image data parameter
[postbody appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"user_image\"; filename=\"image.jpg\"\r\n\r\n"]] dataUsingEncoding:NSUTF8StringEncoding]];
//[postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
**[postbody appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];**
[postbody appendData:[NSData dataWithData:imageData]];
[postbody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"body has %#",postbody);
[request setHTTPBody:postbody];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [postbody length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
NSError *errorReturned = nil;
NSError *error = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
//check netwrok
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&theResponse
error:&errorReturned];
if(data)
{
//parsing json
// again converting into ns dictionary object
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error];
//NSLog(#"post data %#",postbody);
// NSLog(#"response of web ser %# :\n %#",name,jsonArray);
NSLog(#"Response data %#",jsonArray);
// return jsonArray;
}else{
NSLog(#"error %#",error);
}
// return [[NSDictionary alloc]init];
});
This is my web service request.
I am setting content type like
[postbody appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
but still at server side I am getting #content-type =nill
*At server side we used ROR for webservice*
Please help me to solve this.
thanks in advance..
You should be setting content type by header parameters as
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
Please make the change.
For every multipart/form element, you need to set a proper Content-Type, e.g. the following for text-parameters:
[postbody appendData:[[NSString stringWithFormat:#"Content-Type: text/plain;charset=utf-8"] dataUsingEncoding:NSUTF8StringEncoding]];
I am very much new to ios.I have to upload an image to rest server from ios application. I have referred stackoverflow. But everytime the response is 400 which is bad request from client side. I am taking image from device document directory.Could some one post the exact code for image upload.Please refer the code I am using. I am not sure what to use as file name since I am downloading image from documents directory.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:#"urltoupload"]];
NSString *stringBoundary = #"----1010101010";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:attachment; name=\"userfile\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:pngImageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"return Data ---- %#", str);
Try this:
// 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=%#", boundary];
[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", boundary] 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", boundary] 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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set URL
[request setURL:requestURL];
Hope it Helps!!
First convert UIImage to NSData as follows
UIImage *image = [UIImage imageNamed:#"example.png"];
NSData *data = UIImagePNGRepresentation(image);
or
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
Then form your request string
NSURL *url = [NSURL URLWithString:serverURL];
//Time out interval need to be tuned
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [requestString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (!data)
{
NSLog(#"Error downloading data: %#", error);
return;
}
NSError *error1;
NSDictionary *theDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1];
DLog(#"Data received :%#", theDict);
}];