AFNetworking多个文件上传 [英] AFNetworking multiple files upload

查看:131
本文介绍了AFNetworking多个文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些图像上传到服务器,因此我使用AFNetWork发布文件。
代码在这里:

I want to upload some images into the server,so I use AFNetWork to post the files. The code is here:

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

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){.....}

这不行!
但是当我使用下面的代码替换multipartFormRequestWithMethod方法中的for语句时,一切顺利!但如果我无法确认图像数组的数量,我必须使用for语句,我的代码有问题吗?

this is not work! But when I use the code below to replace the "for" statement inside multipartFormRequestWithMethod method, all things went right! but if I couldn't confirm the count of image array,I must use "for" statement,something wrong with my code?

 [formData appendPartWithFileData:UIImageJPEGRepresentation([array objectAtIndex:0], 0.5) name:@"image1" fileName:@"image1.jpg" mimeType:@"image/jpeg"];
 [formData appendPartWithFileData:UIImageJPEGRepresentation([array objectAtIndex:1], 0.5) name:@"image2" fileName:@"image2.jpg" mimeType:@"image/jpeg"];


推荐答案

放置变量 i 在块内。还将文件名从 abc 更改为文件

Put the variable i inside the block. Also changed the name of file from abc to file.

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++;
}
}];

这篇关于AFNetworking多个文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆