AFNetworking Form Request (Multiple File uploads in One Request)

心不动则不痛 提交于 2019-12-01 11:39:32

Use below code to send multiple file to your form. Customize as per your need if required to change anything.

  NSArray *imageArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"close_button.png"],[UIImage imageNamed:@"done_button.png"], nil];
    __block int i=1;
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:@"yoururl"];
    NSMutableURLRequest *request=nil;
        request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"yoururl" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
        {
            for(UIImage *eachImage in imageArray)
            {
                NSData *imageData = UIImagePNGRepresentation(eachImage);
                [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d",i] fileName:[NSString stringWithFormat:@"abc%d.png",i] mimeType:@"image/png"];
                i++;
            }

        }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSData *data = (NSData *)responseObject;
         NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         NSLog(@"Response -> %@",str);

     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error -> %@",[error localizedDescription]);
     }];

On server side I have checked with test.php code, I have just printed print_r($_FILES) and it prints following in my case sorry to keep you guessing.

Response -> Array
(
    [file1] => Array
        (
            [name] => abc1.png
            [type] => image/png
            [tmp_name] => /tmp/phpiWbxSn
            [error] => 0
            [size] => 1997
        )

    [file2] => Array
        (
            [name] => abc2.png
            [type] => image/png
            [tmp_name] => /tmp/phpwtWTE8
            [error] => 0
            [size] => 1847
        )
)

Hope this helps.

Beeka5

I tried the AFHTTPNetwrok solution,but wasn't working, then i added square brackets in "name" key as below and finally images are uploaded successfully. What might me by problem ?

NSData *imageData = UIImageJPEGRepresentation(img,1);
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"images[%d]",i] fileName:[NSString stringWithFormat:@"images%d.jpg",i] mimeType:@"image/jpeg"];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!