Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload multiple images using AFNetworking

I used the PickerController and loaded a few images on to a NSMutableArray.

Now i need to upload all of these images at once. am using AFNetworking and how can i do this?

I went through the AFNetworking documentation and there was a section called Creating an Upload Task for a Multi-Part Request, with Progress. However, i am not able to upload the images that are in my NSMutableArray.

**** NB: I want to upload the images in the NSMutableArray as a Byte Array. How can i do this? ****

The code i have so far,

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

NSURL *URL = [NSURL URLWithString:@"site.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
like image 748
Illep Avatar asked May 12 '15 05:05

Illep


2 Answers

UIImage *image1 = [UIImage imageNamed:@"about_app"];
UIImage *image2 = [UIImage imageNamed:@"alter"];
NSArray *array = @[image1,image2];
NSMutableURLRequest *request = [[AFNetWorkSingleton shareInstance] multipartFormRequestWithMethod:@"POST" path:@"Mindex/getimg" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>formData){
int i = 0;
for(UIImage *eachImage in array)
{
    NSData *imageData = UIImageJPEGRepresentation(eachImage,0.5);
    [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d",i ] fileName:[NSString stringWithFormat:@"file%d.jpg",i ] mimeType:@"image/jpeg"];
    i++;
}
}];

Try this.

like image 192
Hardik Mamtora Avatar answered Sep 18 '22 11:09

Hardik Mamtora


-(void)uploadImages{

// image.finalImage - is image itself
// totalCount - Total number of images need to upload on server

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = @{@"Key":@"Value",@"Key":@"Value"};
[manager POST:serverURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:UIImagePNGRepresentation(image.finalImage) name:@"ImageName" fileName:[[Helper getRandomString:8] stringByAppendingString:@".png"] mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:kNilOptions error:nil];
    _uploadCounter+=1;
    if(_uploadCounter<totalCount){
        [self uploadImages];
    }else {
        NSLog(@"Uploading all images done");
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error");
}];

}

Try this, I have uploaded 10 images on server using this code and its successfully uploaded on sever.

like image 39
Urmi Avatar answered Sep 19 '22 11:09

Urmi