How to post an image using multipart in NSURLSession ios? - ios

Hi i am trying to upload an image through multipart to server in objective c using NSURLSession. But i am getting few errors like
org.apache.commons.fileupload.FileUploadException: Header section has more than 10240 bytes (maybe it is not properly terminated)
Below is my objective c code:
{
NSString *boundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
NSString *fileParamConstant = #"photo";
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
[req setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data;boundary=%#",boundaryConstant];
[req setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n", fileParamConstant, fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *bodyLength = [NSString stringWithFormat:#"%zu",[body length]];
[req setValue:bodyLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPBody:body];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:nil];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:req fromData:body completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(#"STRING %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[uploadTask resume];
}
}
Any help would be greatly appreciated.
Thanks

Related

Not able to get the multipart image in spring from objective c

I got UIImage after that i converted UIImage to JPEG and now again I'm converting into multipart file then I'm passing to spring rest controller
using post and storing that image into my database. but I'm getting null MultipartFile in spring.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:#"myURL"]];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);// image is UIImage
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"unique-consistent-string";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#\r\n\r\n", #"imageCaption"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", #"Some Caption"] dataUsingEncoding:NSUTF8StringEncoding]];
// add image data
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#; filename=imageName.jpg\r\n", #"imageFormKey"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Request reply: %#", requestReply);
}] resume];
I'm passing image like above in objective c
#RequestMapping(value = "/livesessionimage", method = RequestMethod.POST)
#ResponseBody ResponseEntity<Response<String>> livesessionImageUpload(#RequestBody MultipartFile file) throws Exception{
System.out.println("-------------"+file.length());// here i'm getting file null
return "";
}

How to send image attachment to server in post data iOS objective c

Send data to server works in postman but getting error in Objective-C.
I tried to achieve this one failed from server. I referred below links does not work. Getting error upload failed. What am I doing wrong?
Upload image to server ios
how to POST value while uploading image in iOS objective c
My Code:
NSData *dataImage = UIImageJPEGRepresentation(myImage, 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"http://xxxxxxxxxxxxxxxx/index.php/API/uploadClaim";
NSDictionary *user = [[NSUserDefaults standardUserDefaults] objectForKey:#"userDetails"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:#"filename" forKey:#"file_name"];
[_params setObject:#"photo" forKey:#"file_type"];
[_params setObject:[[user objectForKey:#"user_data"] objectForKey:#"id"] forKey:#"user_id"];
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
NSString* FileParamConstant = #"image";
NSURL* requestURL = [NSURL URLWithString:urlString];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:120];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in _params)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
if (dataImage) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] 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:dataImage];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&requestError];
Here is my working code to upload one or multiple image files:
Please note: you should pass images/files data in an NSDictionary with proper key values & You should set key name as your server expecting in upload call.
For example in your case it is file
parameters dictionary will be your other parameters to send with file
- (void) performNetworkEventRequestCallWithFileUpload :(NSMutableDictionary*) imagesData : (NSMutableDictionary*)parameters completionBlock:(void (^)(BOOL succeeded, NSDictionary *dict))completionBlock {
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:BASE_URL]];
[urlRequest setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[urlRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[parameters enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSString *object, BOOL *stop) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",object] dataUsingEncoding:NSUTF8StringEncoding]];
}];
[imagesData enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSData *object, BOOL *stop) {
if ([object isKindOfClass:[NSData class]]) {
if (object.length > 0) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *timeSTamp = [NSString stringWithFormat:#"%#",[NSDate date]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#.jpg\"\r\n",key,timeSTamp] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:object]];
}
}
}];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:body];
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = nil;
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
completionBlock (NO, responseObject);
} else {
NSLog(#"success");
completionBlock (YES, responseObject);
}
}];
[dataTask resume];
}
Here i am using Afnetworking for Uplaoding image us Multipart format, its working fine. So, check it. If its ok for you just vote my answer.
#import "AFHTTPSessionManager.h"
{
NSData * profileData;
}
profileData = UIImageJPEGRepresentation(chosenImage, 1.0);
-(void)UploadImageApi
{
NSString *URLString = #“YourURL”;
/*Profile data is nothing your pick image from gallery or Camera, That saving in profile data.*/
NSMutableDictionary *parameter=[[NSMutableDictionary alloc]init];
[parameter setObject:#“yourObj” forKey:#“YourKey”];
[parameter setObject:#“yourObj” forKey:#“YourKey”];
[parameter setObject:#“yourObj” forKey:#“YourKey”];
if(profileData==nil)
{
[parameter setObject:#"" forKey:#“YourKey”];
}
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
manager.responseSerializer = [AFJSONResponseSerializer
serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager POST:URLString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if(profileData!=nil)
{
[formData appendPartWithFileData:profileData name:#“YourKeyName” fileName:#"filename.jpg" mimeType:#"image/jpeg"];
}
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"%#",responseObject);
NSMutableArray *json = [responseObject mutableCopy];
NSLog(#" success = %#",json);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
}
you can use much simpler approach for data as well as for image:
NSDictionary *headers = #{ #"content-type": #"multipart/form-data; boundary=---------------------------14737809831466499882746641449",
#"cache-control": #"no-cache" };
NSMutableArray *parameters = [[NSMutableArray alloc]initWithObjects:#"param1",#"param2", nil];
NSMutableArray *values = [[NSMutableArray alloc]initWithObjects:#"value1",#"value2", nil];
NSString *boundary = #"---------------------------14737809831466499882746641449";
//NSData *dataImage = UIImageJPEGRepresentation(imageView.image, 1.0f); uncomment for image
NSMutableData *body = [NSMutableData data];
for (int i=0;i<parameters.count;i++) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",[parameters objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",[values objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"Parameters : %#",parameters);
NSLog(#"Values : %#",values);
//image
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\"; filename=\"file.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[NSData dataWithData:dataImage]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://your API URL here"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSMutableArray *array=[[NSMutableArray alloc]init];
rowBtnTableLast2=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"PostMethod Result : %#, PostMethod Error : %#",array,error);
}}];
[dataTask resume];

How to post image on server with dictionary iOS?

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.

How can I send a multipart HTTP request on iOS?

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

Upload xml file to server

I am trying to upload a file like this:
- (NSString *)uploadWithTarget:(NSString *)url andFileData:(NSData *)file andMD5Checksum:(NSString *)checksum andFileName:(NSString *)name
{
uploadFinished = false;
NSString *response = #"";
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];
NSURL * urll = [NSURL URLWithString:url];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:urll];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest addValue:checksum forHTTPHeaderField:#"Md5Hash"];
[urlRequest addValue:#"Keep-Alive" forHTTPHeaderField:#"Connection"];
NSString *boundary = #"*****";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[urlRequest 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]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"%#\"\r\n", name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/xml\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:file]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[urlRequest setHTTPBody:body];
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest];
//[dataTask resume];
NSURLSessionUploadTask *uploadTask = [defaultSession
uploadTaskWithRequest:urlRequest
fromData:file
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (!error && httpResp.statusCode == 200) {
NSLog(#"Request body %#", [[NSString alloc] initWithData:[urlRequest HTTPBody] encoding:NSUTF8StringEncoding]);
} else {
}
}];
[uploadTask resume];
return response;
}
But my Server always responds File not Found! Is that not correct code?!
- (void) uploadLog :(NSString *) filePath
{
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
NSString *urlString =[NSString stringWithFormat:#"http://www.yoursite.com/accept.php"];
// to use please use your real website link.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"_187934598797439873422234";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:#"User-Agent"];
[request setValue:#"http://google.com" forHTTPHeaderField:#"Origin"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"Content-Length %d\r\n\r\n", [data length] ] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"picture\"; filename=\"%#.png\"\r\n", #"newfile"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[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);
}
And here is the php part that works for me.
<?php
$target_path = "./uploads/";
$target_path = $target_path . basename( $_FILES['picture']['name']);
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name'])." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>

Resources