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"]];
}
I am trying to upload image from my app to onedrive using the REST api they provided.
But missing some formating for PST method, please help to work out.
I am doing as,
NSString *urlString = [NSString stringWithFormat:#"https://apis.live.net/v5.0/me/skydrive/files?access_token=%#",oneDriveAccessToken];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"A300x";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//-- Append data into post url using following method
NSMutableData *body = [NSMutableData data];
//-- "image_name" is file name of the image (we can set custom name)
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"file\"; filename=\"%#\"\n",#"name.JPG"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\n\r\n\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:#"--%#--",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
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
I am getting response as:
Result = {
error = {
code = "request_body_invalid";
message = "The request entity body for multipart form-data POST isn't valid. The expected format is:
\n--[boundary]
\nContent-Disposition: form-data; name=\"file\"; filename=\"[FileName]\"
\nContent-Type: application/octet-stream
\n[CR][LF]
\n[file contents]
\n--[boundary]--[CR][LF]";
};
}
I am following this http://msdn.microsoft.com/en-us/library/hh826531.aspx#uploading_files
After suggestions of Jeffery, error message as,
Result = { error = { code = "request_body_invalid"; message = "The
request entity body has an incorrect value in the 'Content-Disposition'
header. The expected format for this value is 'Content-Disposition: form-
data; name=\"file\"; filename=\"[FileName]\"'."; }; }
As a guess, you are mangling the line endings. Sometimes you are using \n sometimes \r\n. You must always use \r\n. As a side note, you shouldn't need the initial \r\n on your first -appendData call. Finally, check your boundary string: they are usually longer to avoid the having those exact same bytes in the content.
NSString *boundary = #"A300x-make-it-longer-to-reduce-risk-12345";
…
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"file\"; filename=\"%#\"\r\n", #"name.JPG"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:#"--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
Here I need to upload the mp3 audio by using the post method, but wrote the code for uploading the audio but i dont know how include the parameters.
kindly check my code and help me to attach parameters.
NSString *baseurl = UploadAudio;
// baseurl = [NSString stringWithFormat:#"%#user_id=%#&comments=%#&login_key=%#",baseurl,[[sharedvar userdict] objectForKey:#"user_id"],[self.audiodict objectForKey:#"comments"],[[sharedvar userdict] objectForKey:#"login_key"]];
NSLog(#"baseurl :%#",baseurl);
NSURL *dataURL = [NSURL URLWithString:baseurl];
NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:dataURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[dataRqst setHTTPMethod:#"POST"];
NSString *stringBoundary = #"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
NSString *headerBoundary = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary];
[dataRqst addValue:headerBoundary forHTTPHeaderField:#"Content-Type"];
NSMutableData *postBody = [NSMutableData data];
// -------------------- ---- Audio Upload Status ---------------------------\\
//pass MediaType file
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; userfile=\"file upload\"; filename=\"uploadaudio.mp3\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: audio/mp3\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//*******************load locally store audio file********************//
NSString *audioUrl = [[self audiodict] objectForKey:#"audiopath"];
NSLog(#"audioUrl :%#",audioUrl);
// get the audio data from main bundle directly into NSData object
NSData *audioData;
audioData = [[NSData alloc] initWithContentsOfFile:audioUrl];
// add it to body
[postBody appendData:audioData];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// final boundary
[postBody appendData:[[NSString stringWithFormat:#"--%#--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
// [postBody appendData:postData];
// add body to post
[dataRqst setHTTPBody:postBody];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:dataRqst delegate:self];
[connection start]; // connection
My parameters are userid and session.Could any body help me for adding these parameters and values
You can use ASIHTTPRequest for sending Audiofiles and additional parameters. It is vary easy to use. Just 2 line of code .It helped me a lot :-)
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setFile:#"YOUR FILE PATH WITH FILE EXTENSION" forKey:#"YOUR FILE KEY"];
Just before the line // final boundary add these lines:
//Append userid
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%#\r\n", myUserID] dataUsingEncoding:NSUTF8StringEncoding]];
use these 3 lines over and over to append more fields e.g. the session field.
I use the below code to post an image to my server.
NSString *localCacheDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Downloads"];
NSString *localPathToSaveFile = [localCacheDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"lion.jpg"]];
NSMutableString *urlForUploadingAttachment = MY_SERVER_URL;
NSData *myData = [NSData dataWithContentsOfFile:localPathToSaveFile];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"--------";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// add image data
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:localPathToSaveFile], 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", #"lion.jpg"] 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]];
}
// setting the body of the post to the reqeust
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:[NSURL URLWithString:urlForUploadingAttachment]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
And in the server side .net application I write the file as
public void SaveAttachment(string filePath, string fileName)
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string fullFilePath = filepath + "\\" + fileName;
using (Stream file = File.OpenWrite(fullFilePath))
{
CopyStream(Request.InputStream, file);
try
{
file.Close();
}
catch (Exception ex) { }
}
}
public void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024]; int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
But the file which is written by the server is corrupted. Even though the file gets written, I cannot open it or preview it. The file size is also as expected. But when I double click the image I get the message that the file is either damaged, corrupted or too large. What is the issue here? Can some one please help me with this?
For image posting by POST Method , here simple code use it as per your requirement:
NSString *imgPath = fullPathOfYourImage;
if([[NSFileManager defaultManager] fileExistsAtPath:imgPath])
{
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"photo\"; filename=\"YourImageName.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
^..YourImageName….^
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithContentsOfFile:imgPath]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
I have a question regarding to the code that OCRApiService.com provides to devs.
This is the code they provide:
//author : Altaf A. M.
//Code Snippet to convert the captured/picker'd (sic) image via OCRApiService
//Input parameter: UIImage
//output parameter: NSString
//updates possible(rather necessary): integrate it asynchronously
- (NSString *) upload:(UIImage *)myImage
{
NSString *urlString = #"http://api.ocrapiservice.com/1.0/rest/ocr";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// file
// NSData *imageData = UIImagePNGRepresentation(myImage);
NSData *imageData = UIImageJPEGRepresentation(myImage, 1.0);
[body appendData:[[NSString stringWithFormat:#"--%#", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: attachment; name=\"image\"; filename=\".jpg\""] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithString:#""] dataUsingEncoding:NSUTF8StringEncoding]];
// Text parameter1
NSString *param1 = #"en";
[body appendData:[[NSString stringWithFormat:#"--%#", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"language\""] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#""] dataUsingEncoding:NSUTF8StringEncoding]];
// Another text parameter
NSString *param2 = #"YOUR_API_KEY";
[body appendData:[[NSString stringWithFormat:#"--%#", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"apikey\""] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param2] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#""] dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnedString = [[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] autorelease];
// NSLog(#"received string = %#", returnString);
// UIAlertView *returnedText = [[UIAlertView alloc] initWithTitle:#"Returned Text" message:[NSString stringWithFormat:#"%#", returnString] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
// [returnedText show ];
// [returnedText release];
return returnedString;
}
I put in my API Key but the problem is whenever I call this method, I get
received string = HTTP/1.1 400 Bad Request
The language parameter is missing
According to the docs, I have set the language correctly but I am not sure why it is still coming up with this error message...
Thanks!
I am the owner of ocrapiservice.com.
The api is working but there is a bug in the code snippet.
Could you please open an issue on https://github.com/smart-mobile-software/ocrapiservice/issues ?
We will correct it within the week.