I want to send my image with parameter (username, password..etc) ?? following is my code:
-(void) senRequestForPostAnswerWithImage:(NSString *)imageName andAnswer:(NSString *)answer andQuestionID:(NSString *)questionID
{
NSUserDefaults *loginData = [NSUserDefaults standardUserDefaults];
NSString *username = [loginData objectForKey:#"username"] ;
NSString *password = [loginData objectForKey:#"password"];
NSString *postString = [NSString stringWithFormat:#"&username=%#&password=%#&image=%#&answer=%#&question_id=%#", username, password, imageName, answer, questionID];
NSString *urlString = #"http://myAPIName/MethodName";
NSURL *myURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *detailRequestToServer =[NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[detailRequestToServer setHTTPMethod:#"POST"];
[detailRequestToServer setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
const char *utfString = [postString UTF8String];
NSString *utfStringLenString = [NSString stringWithFormat:#"%zu", strlen(utfString)];
[detailRequestToServer setHTTPBody:[NSData dataWithBytes: utfString length:strlen(utfString)]];
[detailRequestToServer setValue:utfStringLenString forHTTPHeaderField:#"Content-Length"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:detailRequestToServer delegate:self];
if (theConnection)
{
self.responseData = [[NSMutableData alloc] init];
[GeneralClass startHUDWithLabel:#"Loading…"];
}
else
NSLog(#"Connection Failed!");
}
I know there are many question on this site but I don't know where and what I need to change in my existing code ??
So, please suggest me what I need to change in my existing code for add functionality of send image ??
NOTE: without image this above code is working well for me.
My suggestion would be to use AFNetworking. It will simplify the process for your considerably and save you a lot of time. It is widely used framework by developers.
https://github.com/AFNetworking/AFNetworking
You can easily send image with parameters using just few lines (POST-multipart request):
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
[manager POST:#"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
As far as I know, you can't directly send it as UIImage. You need to convert it to NSData, which the gets decoded on the server side.
Another alternative, is to upload the image somewhere, which can be accessed via a URL. (But this is usually done on the server side and the URL is given back as response).
There's a post here about converting UIImage to NSData.
using this you can pass parameters as well as with image data.
NSString *urlString = [NSString stringWithFormat:#"http://myAPIName/MethodName/test.php&username=%#&password=%#&image=%#&answer=%#&question_id=%#", username, password, imageName, answer, questionID];
NSLog(#"MyURL: %#",urlString);
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *str=[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"SourceImage\"; filename=\"Image_%#\"\r\n",[imagePath lastPathComponent]];
[body appendData:[[NSString stringWithString:str] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithContentsOfFile:imagePath]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
If you want to send parameter with image by post method then use following code. Its working very well for me..
I tried to change my code as per your requirement, follow it.
You need to create NSMutableDictionary and add your parameter on it and also append this dictionary to NSMutableData as JSON formate. (You need to add NSMutableData Library to your project)
-(void) senRequestForPostAnswerWithImage:(NSString *)imageName andAnswer:(NSString *)answer andQuestionID:(NSString *)questionID
{
NSUserDefaults *loginData = [NSUserDefaults standardUserDefaults];
NSString *username = [loginData objectForKey:#"username"] ;
NSString *password = [loginData objectForKey:#"password"];
// create NSMutableDictionary for store parameter
NSMutableDictionary *dicOfData = [[NSMutableDictionary alloc] init];
[dicOfData setObject:username forKey:#"username"];
[dicOfData setObject:password forKey:#"password"];
[dicOfData setObject:imageName forKey:#"imageName"];
[dicOfData setObject:answer forKey:#"answer"];
[dicOfData setObject:questionID forKey:#"questionID"];
NSString *url = #"http://myAPIName/MethodName";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
/// create NSMutableData to store data of dictionary
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"--iOS Boundary Line--";
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField: #"Content-Type"];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *imgPath = [documentsDir stringByAppendingPathComponent:imageName];
if([imageName length] > 0)
{
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=\"%#\"\r\n", imageName] dataUsingEncoding:NSUTF8StringEncoding]];
[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]];
}
}
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"requestData\"\r\n\r\n%#", [dicOfData JSONRepresentation] ] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", [body length]] forHTTPHeaderField:#"Content-Length"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection)
{
self.responseData = [[NSMutableData alloc] init];
}
else
NSLog(#"Connection Failed!");
}
At your server (PHP) side.. you get image (object and name if you added) with other parameter in dictionary formate.
Refer this code - It works perfect for me -
NSString *userID = mainDelegate.loginUserPin;
UIImage *imag = self.addImage;
NSString *urlString = mainDelegate.I2K2_Webservice_Url;
NSData *imageData = UIImageJPEGRepresentation(imag, 90);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:6*60000];
NSString *boundary = #"*****";
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]];
//Title
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"title\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#~%#",userID,txtName.text] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//Description
[body appendData:[#"Content-Disposition: form-data; name=\"description\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *imgNameString = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"%#~%#\"\r\n",userID,txtName.text];
NSLog(#"imgNameString : %#",imgNameString);
[body appendData:[[NSString stringWithString:imgNameString] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",returnString);
You cant send UIImage by specifying it's name to web server. You should include it in the HTTP body as NSData .I used ASIHTTPRequest, it was simple and perfect. Use ASIHTTPRequest. A sample code is given below
NSData *imgData = UIImageJPEGRepresentation(IMAGE_HERE, 0.9);
formReq = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
formReq.delegate = self;
[formReq setPostValue:VALUE1 forKey:KEY1];
[formReq setPostValue:VALUE2 forKey:KEY2];
if (imgData) {
[formReq setData:imgData withFileName:#"SAMPLE.jpg" andContentType:#"image/jpeg" forKey:IMAGE_KEY];
}
[formReq startSynchronous];
Related
I've looked into a good number of articles on how to do a multipart/form-data POST on iOS, but none really explain what to do if there were normal parameters as well as the file upload.
I have used the multipart/form-data POST on iOS & I had written the following code and it is uploading data but not image data
- (void)postWithImage:(NSDictionary *)dictionary
{
NSString *urlString = [NSString stringWithFormat:#"YourHostString"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *boundary = #"----1010101010";
// define content type and add Body Boundry
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSEnumerator *enumerator = [dictionary keyEnumerator];
NSString *key;
NSString *value;
NSString *content_disposition;
while ((key = (NSString *)[enumerator nextObject])) {
if ([key isEqualToString:#"file"]) {
value = (NSString *)[dictionary objectForKey:key];
NSData *postData = UIImageJPEGRepresentation([UIImage imageNamed:value], 1.0);
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\";\r\nfilename=\"screen.png\"\r\n\r\n",value] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:postData];
} else {
value = (NSString *)[dictionary objectForKey:key];
content_disposition = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key];
[body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value options:NSJSONWritingPrettyPrinted error:&error];
[body appendData:jsonData];
//[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close the request body with Boundry
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", body.length] forHTTPHeaderField: #"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
Can anyone please help me to get why image data is not uploading
I think you should append #"content-Type" before you append real data, like this:
[body appendData:[#"Content-Type: image/png\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
I have a dictionary (dict) of some keys/values and an image. Now I want to upload image to server with dictionary. I have already try this but not getting any success. Here is my sample code--
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"];
NSData *imageData = UIImageJPEGRepresentation(image,0.5);//or you can use png representation- UIImagePNGRepresentation(image);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"thumbnail\"; filename=\"image.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter all_data
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"all_data\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",dict] 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 request
[request setHTTPBody:body];
NSError *error=nil;
NSHTTPURLResponse *response=nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I need help where is I'm going wrong.. Thanks in advance
Try out the below code:
-(void)uploadImage:(NSString *)api :(NSDictionary *)params : (UIImage *)image {
NSURL *myURL = [NSURL URLWithString:api];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:myURL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#; charset=UTF-8", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *theBodyData = [NSMutableData data];
for (int i=0; i<[[params allKeys] count]; i++)
{
[theBodyData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *value=#"";
value=[params objectForKey:[[params allKeys] objectAtIndex:i]];
NSString * value1=[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#\r\n\r\n%#\r\n",[[params allKeys] objectAtIndex:i],value];
[theBodyData appendData:[value1 dataUsingEncoding:NSUTF8StringEncoding]];
}
[theBodyData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[#"Content-Disposition: form-data; name=\"my_file1\"; filename=\"image1.jpeg\"\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[theBodyData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
NSData *myData = UIImageJPEGRepresentation(image,0.5);
[theBodyData appendData:[NSData dataWithData:myData]];
[theBodyData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:theBodyData];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", (int)[theBodyData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: theBodyData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Server Raw Response : %#",responseString);
}
}];
[dataTask resume];
}
Your code looks fine but I think you have to convert your dictionary into json string. Just Replace this line-
[body appendData:[[NSString stringWithFormat:#"%#",dict] dataUsingEncoding:NSUTF8StringEncoding]];
with
NSString *jsonStr = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
[body appendData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
may be this will help you.
I am trying to upload a photo onto a server on my iOS App using multipart method. However, I can't seem to get it to work. I am getting the error:
At least one of the pre-conditions you specified did not hold. Bucket POST must be of the enclosure-type multipart. I've looked this error and can't seem to figure out how I can solve this problem on my end. The Android version of the app works so the API should not be the problem?
Here is my code:
//photo file
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filePath];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:uploadInfo.key forKey:#"key"];
[_params setObject:uploadInfo.aaki forKey:#"AWSAccessKeyId"];
[_params setObject:uploadInfo.acl forKey:#"acl"];
[_params setObject:uploadInfo.policy forKey:#"policy"];
[_params setObject:uploadInfo.signature forKey:#"signature"];
[_params setObject:uploadInfo.success_action_status forKey:#"success_action_status"];
[_params setObject:#"image/jpeg" forKey:#"Content-Type"];
NSURL* requestURL = [NSURL URLWithString:uploadInfo.path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"%#", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
if (data) {
[body appendData:data];
}
[request setHTTPBody:body];
[request setURL:requestURL];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
Try as below.
//photo file
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filePath];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:uploadInfo.key forKey:#"key"];
[_params setObject:uploadInfo.aaki forKey:#"AWSAccessKeyId"];
[_params setObject:uploadInfo.acl forKey:#"acl"];
[_params setObject:uploadInfo.policy forKey:#"policy"];
[_params setObject:uploadInfo.signature forKey:#"signature"];
[_params setObject:uploadInfo.success_action_status forKey:#"success_action_status"];
NSURL* requestURL = [NSURL URLWithString:uploadInfo.path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[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"];
NSMutableData *body = [NSMutableData data];
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]];
}
NSString *FileParamConstant = #"image"; // Key of webservice in which you need to send image
// add image data
if (data) {
[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:data];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setURL:requestURL];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Try with another simple code.
NSDictionary *aParams =#{}; //your param dictionary here
UIImage *aImage = [UIImage imageNamed:#"your image here"]; //set yout image here
NSString *aStrParamName = #"image parameter name here";// set parameter name of image here
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"uploadInfo.path"]];// url here
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:30];
NSString *uuidStr = [[NSUUID UUID] UUIDString];
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", uuidStr] forHTTPHeaderField:#"Content-Type"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSData *imagedata = UIImageJPEGRepresentation(aImage, (CGFloat)0.6);
NSData *fileData = UIImagePNGRepresentation([UIImage imageWithData:imagedata]);
NSData *data = [self createBodyWithBoundary:uuidStr withDictData:aParams data:fileData filename:aStrParamName];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSAssert(!error, #"%s: uploadTaskWithRequest error: %#", __FUNCTION__, error);
// parse and interpret the response `NSData` however is appropriate for your app
NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"ResponseString:%#",aStr);
NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"responce:%#",aMutDict);
});
}];
[task resume];
also add below method
- (NSData *)createBodyWithBoundary:(NSString *)boundary withDictData:(NSDictionary *)aDict data:(NSData*)data filename:(NSString *)paramName
{
NSMutableData *body = [NSMutableData data];
if (data) {
//only send these methods when transferring data as well as username and password
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n", paramName,#"image.png"] dataUsingEncoding:NSUTF8StringEncoding]];
#warning if you have to chane name of image then change. if there is any error then chane other wise go as it is..
[body appendData:[[NSString stringWithFormat:#"Content-Type: %#\r\n\r\n", #"image/png"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
for (NSString *aKey in aDict.allKeys) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n%#\r\n", aKey,aDict[aKey]] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
return body;
}
I am trying to take picture and send to data base (json using post method) in ios
-(IBAction)upload:(id)sender
{
// NSData *imageData = UIImagePickerControllerCameraCaptureModePhoto;
// UIImagePNGRepresentation(yourImage);
NSData *imageData = UIImageJPEGRepresentation(imageview.image,0.8);
NSString *urlString = [ NSString stringWithFormat:#"https://www.******/xyz/jsonurl.php?action=insert&lat=80.2626&long=29.64565&cat=1¬e=&date=&sdkuserid=12345&nick_name=sandy&place_address=pluto&p_id=3&intid=%d,&name=userfile&filename=%#",1,imageData];
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:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%d\"\r\n", 1]] 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];
NSLog(#" body %#",body);
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
Try this code and give me response
-(IBAction)upload:(id)sender
{
NSData *imageData = UIImageJPEGRepresentation(imageview.image,0.8);
NSString *urlString = [ NSString stringWithFormat:#"https://www.******/xyz/jsonurl.php?action=insert&lat=80.2626&long=29.64565&cat=1¬e=&date=&sdkuserid=12345&nick_name=sandy&place_address=pluto&p_id=3&intid=1"];
urlString =[[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:Urlstr]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyyMMdd_hhmmss"];
NSString * fileName =[NSString stringWithFormat:#"%#",[formatter stringFromDate:[NSDate date]]];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"New%#.png\"\r\n",fileName] 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 *ImageString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
}
Here is the solution :
-(void)uploadImageOnServer:(NSData *)imageData forId:(NSString *)imageId
{
NSURL *strURL = myUrl; //here is your url
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:strURL];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------147378098314876653456641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *stringData = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"Documents\"; filename=\%#.png\r\n",imageId];
[body appendData: [stringData 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];
// 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);
}
Here 'Documents' is your folder name where you want to save this image to your backend server. Hope this helps you.... Enjoy!
I tried AFNetworking's "Create an upload task" and this to upload image in .net server, but couldn't. This is what I tried.
- (void)uploadJPEGImage:(NSString*)requestURL image:(UIImage*)image
{
NSURL *url = [[NSURL alloc] initWithString:requestURL];
NSMutableURLRequest *urequest = [NSMutableURLRequest requestWithURL:url];
[urequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[urequest setHTTPShouldHandleCookies:NO];
[urequest setTimeoutInterval:60];
[urequest setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[urequest setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// add image data
NSData *imageData = UIImageJPEGRepresentation(qrCodeImage.image, 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", pictureName] 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]];
[urequest setHTTPBody:body];
NSLog(#"Check response if image was uploaded after this log");
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:urequest returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
Since AFNetworking code gives, me this run time error despite adding
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:#"application/xml", #"text/xml", #"text/html", nil];
Thanks.
Your code was missing the __VIEWSTATE content par. I've added in code to extract the URL of the uploaded image at the end:
- (void)uploadJPEGImage:(NSString*)requestURL image:(UIImage*)image
{
NSURL *url = [[NSURL alloc] initWithString:requestURL];
NSMutableURLRequest *urequest = [NSMutableURLRequest requestWithURL:url];
[urequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[urequest setHTTPShouldHandleCookies:NO];
[urequest setTimeoutInterval:60];
[urequest setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[urequest setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// Add __VIEWSTATE
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"__VIEWSTATE\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"/wEPDwUKLTQwMjY2MDA0M2RkXtxyHItfb0ALigfUBOEHb/mYssynfUoTDJNZt/K8pDs=" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// add image data
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"FileUpload1\"; filename=\"image.jpg\"\r\n" 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]];
[urequest setHTTPBody:body];
NSLog(#"Check response if image was uploaded after this log");
//return and test
NSHTTPURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:urequest returningResponse:&response error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
// Extract the imageurl
NSArray *parts = [returnString componentsSeparatedByString:#"\r\n"];
if (parts.count > 0) {
NSError *error = NULL;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[parts[0] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#", result[#"imageurl"]); // Will either be nil or a URL string
}
}
1.I think you miss the hidden input in upload page:
2.Using the code below, i can upload successfully and get the right response string:
UIImage *image = [UIImage imageNamed:#"a.jpg"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer new];
// add hidden parameter here
NSDictionary * parameters = #{#"__VIEWSTATE":#"/wEPDwUKLTQwMjY2MDA0M2RkXtxyHItfb0ALigfUBOEHb/mYssynfUoTDJNZt/K8pDs="};
[manager POST:#"http://cnapi.iconnectgroup.com/upload/fileuploadnew.aspx" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// add image date here
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.5) name:#"FileUpload1" fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData * data = (NSData *)responseObject;
NSLog(#"Success,Response string: %#", [NSString stringWithCString:[data bytes] encoding:NSISOLatin1StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];