0

I am trying to post two images to an url using multipart post request in Objective C , From my code I can able to send only one image, How to send two images to the url, using multipart / form data I have tried so many example for this bur I did not get the result I want

-(void)processPostMultipartRequestNew{
 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

NSString *urlStr =  [self.dataModel.apiUrl 
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr = [urlStr 
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr= [urlStr stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];



NSURL *reqUrl = [NSURL URLWithString:urlStr];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:reqUrl];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];



NSDictionary *requestBody = self.dataModel.requestParams2;
UIImage *imageToUpload = [requestBody objectForKey:keyUploadImage];


NSDictionary *requestBody2 = self.dataModel.requestParams;

UIImage *imageToUpload2 = [requestBody2 objectForKey:keyUploadImage];
    if(requestBody){
    NSData *imageData = UIImageJPEGRepresentation(imageToUpload, 0);//no compression by default
    NSData *imageData2 = UIImageJPEGRepresentation(imageToUpload2, 0);

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Disposition: attachment; name=\"uploadedfile1\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: attachment; name=\"uploadedfile2\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[NSData dataWithData:imageData2]];

    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];





    // Text parameter1
    NSString *param1 = @"111";
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"SyncId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:body];
}

[request setHTTPShouldHandleCookies:NO];
[request setHTTPMethod:REQUEST_TYPE_POST];
[request setTimeoutInterval:60*4];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {


     NSLog(@"completionHandler with response:%@",[NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse*)response statusCode]]);
     NSLog(@"reponse: %ld",(long)[(NSHTTPURLResponse*)response statusCode]);

     NSInteger status = [(NSHTTPURLResponse*)response statusCode];

     if(error){
         NSLog(@"http request error: %@", error.localizedDescription);
         // handle the error
     }
     else{
         if (status == 201){
             // handle the success
         }
         else{
             NSLog(@"error");
         }   // handle the error
     }
     if(!data || data == nil)
         return ;
     NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

     NSDictionary *resultDict  =(NSDictionary *) [NSJSONSerialization
                                                  JSONObjectWithData:data options:NSJSONReadingAllowFragments
                                                  error:&error];

     //NSDictionary *resultDict  =(NSDictionary *) [NSJSONSerialization JSONObjectWithStream:data options:kNilOptions error:&error];

     self.dataModel.responseData =resultDict;
     NSLog(@"error is %@",error);
     NSLog(@"data is %@",data);

     {

     if(!data || data == nil)
         return ;
     NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
     //for failed case
     if(error || error != nil){
         self.dataModel.responseFailed = YES;
         self.dataModel.error = error;
         NSLog(@"Result in error case %@",[[error userInfo] objectForKey:@"NSDebugDescription"]);
         [self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
     }
     else{
         self.dataModel.responseFailed = NO;
         self.dataModel.error = nil;
         NSString  *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         if(!([response rangeOfString:@".jpg"].location==NSNotFound))
         {
             NSString *res=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
             self.dataModel.responseData =res;
             [self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
         }

     }
     }
     self.executing = NO;
     [self setFinishedState:YES];
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

     [self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];

 }];
  }

Is this a right way to do? if not how can I get success in this. Thanks in advance.

1
  • I tried @Sh_Khan answer and I am getting the error response as Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.} How to fix this? Commented Jan 26, 2018 at 10:11

2 Answers 2

1

Yes you can like this Edit ///////////////////////////////

      // Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:@"ios" forKey:@"device_type"];
[_params setObject:@"user" forKey:@"type"];
[_params setObject:"iddddd" forKey:@"user_id"];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ


// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@"http........"];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in [_params allKeys]) {
    [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 txt data

/////////////////////////////

 NSArray *allImagesData= @[UIImagePNGRepresentation(imageToUpload) ,UIImagePNGRepresentation(imageToUpload2)];

NSLog(@"files array before %@", allImagesData);

for (int i=0; i<[allImagesData count]; i++)
{ 
    NSString*filename=[NSString stringWithFormat:@"image%d.jpeg",i+1];

    NSString* FileParamConstant = [NSString stringWithFormat:@"image%d",i+1];

    NSData *imageData = allImagesData[i];      

    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:[@"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", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];


}
Sign up to request clarification or add additional context in comments.

10 Comments

How to add my images to that filePathArray, U have not mentioned any where?
it's the path where my files were , you can change the path directly to your images
change it to 2 if you want to upload 2 images
I am getting the images as data then how to add this data to array
I tried this and I am getting the error response as Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.} How to fix this?
|
0

U can do like this:

-(void)PostUrlCall_Multipart_Image:(NSString *)IN_URL Param:(NSDictionary*)IN_Param Image:(UIImage *)image
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

    [manager POST:IN_URL parameters:IN_Param constructingBodyWithBlock:^(id<AFMultipartFormData> formData){

        [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 1.0) name:@"image" fileName:@"image" mimeType:@"image/jpeg"];

    }
    progress:nil
    success:^(NSURLSessionDataTask *task, id responseObject) {
        m_Status=1;
        self.dic_Response = (NSDictionary *)responseObject;
        [[NSNotificationCenter defaultCenter] postNotificationName:m_strPostMsg object:self];

    }
    failure:^(NSURLSessionTask *operation, NSError *error){
        m_Status=0;
        self.dic_Response=[[NSMutableDictionary alloc]init];
//        [self.dic_Response setValue:@[Time_Out_Msg] forKey:@"@[Time_Out_Msg]"];
        NSLog(@"Error %@",error);
        [[NSNotificationCenter defaultCenter] postNotificationName:m_strPostMsg object:self];
    }];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.