send image along with other parameters with AFNetworking

19,518

Solution 1

I have used same AFNetworking to upload image with some parameter. This code is fine working for me. May be it will help out

NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);//(uploadedImgView.image);
if (imageToUpload)
{
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, @"keyName", nil];

    AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://------"]];

    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"API name as you have" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData: imageToUpload name:@"image" fileName:@"temp.jpeg" mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
         //NSLog(@"response: %@",jsons);

     }
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if([operation.response statusCode] == 403)
         {
             //NSLog(@"Upload Failed");
             return;
         }
         //NSLog(@"error: %@", [operation error]);

     }];

    [operation start];
}

Good Luck !!

Solution 2

With AFNetworking 2.0.1 this code worked for me.

-(void) saveImage: (NSData *)imageData forImageName: (NSString *) imageName {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSString *imagePostUrl = [NSString stringWithFormat:@"%@/v1/image", BASE_URL];
    NSDictionary *parameters = @{@"imageName": imageName};

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:imagePostUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"image" fileName:imageName mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *op = [manager HTTPRequestOperationWithRequest:request success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        DLog(@"response: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"Error: %@", error);
    }];
    op.responseSerializer = [AFHTTPResponseSerializer serializer];
    [[NSOperationQueue mainQueue] addOperation:op];
}

If JSON response is needed use:

op.responseSerializer = [AFJSONResponseSerializer serializer];

instead of

op.responseSerializer = [AFHTTPResponseSerializer serializer];
Share:
19,518
Malloc
Author by

Malloc

Updated on June 17, 2022

Comments

  • Malloc
    Malloc about 2 years

    I am updating an old application code which used ASIHTTPRequest with AFNetworking. In my case, I am sending a bench of data to API, these data are different types: Image and other.

    Here is the code I adopt so far, implementing an API client, requesting a shared instance, prepare the params dictionary and send it to remote API:

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"Some value" forKey:aKey];
    
    [[APIClient sharedInstance]
     postPath:@"/post"
     parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
         //some logic
    
    
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         //handle error
    
     }];
    

    What would be the case when I want to add an image to the params dictionary?

    With ASIHTTPRequest, I used to do the following:

    NSData *imgData = UIImagePNGRepresentation(anImage);
    
    NSString *newStr = [anImageName stringByReplacingOccurrencesOfString:@"/"
                                                                  withString:@"_"];
    
    
    
    [request addData:imgData
        withFileName:[NSString stringWithFormat:@"%@.png",newStr]
      andContentType:@"image/png"
              forKey:anOtherKey];
    

    I digged into AFNetworking documentation and found they appending the image in an NSMutableRequest like this:

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
    }];
    

    How should I mix this together on a neat way to integrate my image data into the APIClient request? Thanx in advance.

  • Malloc
    Malloc about 11 years
    Hi, where do you put the key for the image? Thanx.
  • Ajay Chaudhary
    Ajay Chaudhary about 11 years
    @"image" is the key for any image that you want to upload.
  • jerik
    jerik over 10 years
    AFHTTPClient is splitted into AFHTTPRequestOperationManager & AFHTTPSessionManager. It does not exist anymore in 2.0.
  • Shikhar varshney
    Shikhar varshney about 9 years
    what do I specifically put in the path parameter?