6

I've been looking examples for the new AFNetworking 2.0 to upload images. But I'm hitting wall and couldn't figure out what's wrong with the code. So this is the code I used

NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];


AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://myserverurl.com"];

NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromData:imageData progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];

TIA

ordinaryman09
  • 2,761
  • 4
  • 26
  • 32

1 Answers1

34

I ended up using the multi-part request

UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFormData:imageData name:@"image"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
atlex2
  • 2,548
  • 1
  • 14
  • 19
ordinaryman09
  • 2,761
  • 4
  • 26
  • 32
  • 3
    `appendPartWithFileData:imageData name:@"image" error:nil]` is not working anymore, I guess. You should use: `[formData appendPartWithFormData:imageData name:@"image"];` ...but still it doesn't work for me :/ – raistlin Nov 07 '13 at 14:43
  • 4
    and why do you even bother with fileURl if you're not using it after? – raistlin Nov 07 '13 at 14:44
  • 2
    @raistlin `appendPartWithFileData` worked for me as well. see http://stackoverflow.com/a/20190352/1933185 – jerik Nov 25 '13 at 10:59
  • 2
    @raistlin I think you mean "filePath," which indeed does not seem to be used here. – carbocation May 24 '14 at 05:25
  • @ordinaryman09 do u know how to add Header values with an image? – Ushan87 Jan 29 '15 at 10:41
  • In my case it worked after add this: `[formData appendPartWithFileData:img_data name:@"add_file[]" fileName:@"abc.png"mimeType:@"image/png"];` – Bhavin Ramani Jun 04 '16 at 12:07