How to POST Multiple images on the server? - ios

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

Related

How can I call didSendBodyData method and how to update on progress bar?

How can I send byte data to another viewcontroller and use it on progressbar?
How can I upload video and set progressbarview as per indexpathrow which I selected?
Here is my code:
-(void)updateUserVideoResponse:(NSMutableDictionary*)params ImageFile:(NSData*)Img Completion:(void (^)(NSData *data,
NSURLResponse *response, NSError *error))callback;
{
NSLog(#"Params %#",params);
NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",VideoAddResponseUrl,[params objectForKey:#"id"]]];
// NSString *accessToken=[[AccessToken classMethodeOfAccessToken] getAccessToken];
// NSData *webData = UIImageJPEGRepresentation(imageProfile,0.5);
NSLog(#"%.2f",(float)Img.length);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:myURL];
[request setHTTPMethod:#"PUT"];
NSString *boundary = #"_187934598797439873422234";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
// NSString *contentType = #"application/json";
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#.mov\"\r\n",[params objectForKey:#"question"],[params objectForKey:#"question"]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:Img]];
// [body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"video-size\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%.2f",(float)Img.length] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"camera_resolution\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"AVCaptureSessionPresetLow"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSLog(#"Request body %#", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
[request addValue:[NSString stringWithFormat:#"%lu", (unsigned long)[body length]] forHTTPHeaderField:#"Content-Length"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:callback] resume];
}
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
NSLog(#"progress/total %f",progress/total);
}

Sending NSData and NSString in the same POST

I am trying to follow this Insert imagedata into MySQL database from XCode using PHP & JSON answer to send a photo from my app to a MySQL database but I am confused as to how to add an NSString ID to reference to the POST body.
We have the following to create the body which gets the image data:
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\"; filename=\"imagename.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]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
How might I send additional information such as a text ID within the same post?
Here is the whole code to post data along with Imagedata and string.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[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:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\"; filename=\"imagename.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];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"<YOUR TEXT>" forKey:#"<KEY>"];
[body appendData:[self createFormData:dict withBoundary:boundary]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
- (NSData*)createFormData:(NSDictionary*)myDictionary withBoundary:(NSString*)myBounds
{
NSMutableData *myReturn = [[NSMutableData alloc] init];
NSArray *formKeys = [myDictionary allKeys];
for (int i = 0; i < [formKeys count]; i++) {
[myReturn appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",myBounds] dataUsingEncoding:NSASCIIStringEncoding]];
[myReturn appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n%#",[formKeys objectAtIndex:i],[myDictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSASCIIStringEncoding]];
}
return myReturn;
}
I think what you are looking for is setValue:forHTTPHeaderField:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.example.com"]];
request.HTTPMethod = #"POST";
request.HTTPBody = body;
[request setValue:#"someValue" forHTTPHeaderField:#"someField"];

Upload multiple images in one request

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
{
}
}

Error while uploading file

I m uploading image using post method but every time i find following error:
The operation couldn’t be completed. (NSURLErrorDomain error -1012.)
Please suggest me the way by which i can resolve this issue:(
NSString *urlString = [NSString stringWithFormat:#"%#%#",Base_URL,URL_Upload];
NSURL* requestURL = [NSURL URLWithString:urlString];
NSString *filename = imageName;
//creating request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
// set URL
[request setURL:requestURL];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *postbody = [NSMutableData data];
NSData* imageData = UIImageJPEGRepresentation(image, 1);
if (imageData) {
[postbody appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString* fileData = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n", filename];
NSLog(#"fileData %#",fileData);
[postbody appendData:[fileData dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:imageData];
[postbody appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[postbody appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:postbody];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [postbody length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[_connection start];
if (_connection) {
_reposnseData = [NSMutableData data];
}
NSString *str=[NSString stringWithFormat:#"%#registration.php",appdel.baseUrl];
NSString *urlString = [NSString stringWithFormat:#"%#",str];
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"];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imgData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter username
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"username\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[userName.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter token
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[eMail.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"pass\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[passWord.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter method
NSLog(#"%#",countryCode);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"country\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[countryCode dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
NSString *urlString = [NSString stringWithFormat:#"http://********/web-services/register_user.php?firstname=%#&lastname=%#&email=%#&password=%#&location=india&device=IPHONE",details.fname,details.lname,details.emailAddress,details.password];
// urlString=[urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
UIImage *image=details.pic;
NSData *imageData =UIImageJPEGRepresentation(image, 0.1);
double my_time = [[NSDate date] timeIntervalSince1970];
NSString *imageName = [NSString stringWithFormat:#"%d",(int)(my_time)];
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"profile_pic\"; filename=\"", imageName, #".jpg\"\r\n\""];
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:[[NSString stringWithString:string] 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*s11= [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *responseDictionary1;
responseDictionary1 = [XMLReader dictionaryForXMLString:s11 error:nil];

Attaching an image and posting to a JSON API

How can I create a post with an image and attach it as a featured image from iPhone app?
I am using wordpress with JSON API plugin
My url to create post: <-- Reference to this
http://www.example.com/api/create_post/?nonce=eea4bb4ce5&status=publish&title=Test&content=test%20content&categories=animals
Now I need to attach an image from the phone gallery to this url. How can I do this?
Try this. Use JSON POST method. You can append all your parameters like this.
-(void)uploadImage
{
NSString *method = #"";
NSString *username = #"";
NSString *token = #"";
NSString *urlString = [NSString stringWithFormat:#"%#",#"yoururl"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
// file
NSData *imageData = UIImageJPEGRepresentation( imageView.image, 0.8);
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"image\"; filename=\".jpg\"\r\n"] 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 stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// parameter username
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"username\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[username dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// parameter token
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"auth_token\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[token dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// // parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"method\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[method dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",returnString);
[returnString release];
}
Hope this may help you.
To full fill your requirement you need to send image file on web-service using by POST method
First chose image from Photo Library or take it from the camera and make data of that Image using following code.
NSString *imgName = [NSString stringWithFormat:#"ImageTest"];
NSData *imgData=UIImagePNGRepresentation(imgView.image);
NSString* urlstring = [NSString stringWithFormat:#"http://www.example.com/api/create_post/?nonce=eea4bb4ce5&status=publish&title=Test&content=test%20content&categories=animals&imageFile=%#",imgName];
NSLog(#"URL >> %#",urlstring);
NSURL url = [NSURL URLWithString:[urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//===============================================
NSMutableURLRequest postRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[postRequest setURL:url];
[postRequest setHTTPMethod:#"POST"];
NSString boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[postRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [[NSMutableData alloc] init];
[postRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"userfile\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
imgName this is very important object in this code it's image which you need to pass in your web service which is shown as above.
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",imgName]] dataUsingEncoding:NSUTF8StringEncoding]]; //img name
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Add Image imgData is Declare as Above.
[body appendData:[NSData dataWithData:imgData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postRequest setHTTPBody:body];
NSURLResponse *response;
NSError error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error];
NSString *result=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSString * jsonRes = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"result = %#",[result JSONValue]);
It perfectly working with me ! I hope you may get help from here!

Resources