使用 AFNetworking 上传多个图像或文件,
Posted
技术标签:
【中文标题】使用 AFNetworking 上传多个图像或文件,【英文标题】:Upload multiple Image or File using AFNetworking, 【发布时间】:2018-08-06 11:31:04 【问题描述】:我想使用 AFNetworking 上传多张图片。 像这样Please Check This Image
我附上了邮递员的例子。
我的代码:
NSString *key = [[mediaInfo allKeys] objectAtIndex:0];
NSDictionary *dict = [[mediaInfo objectForKey:key] objectAtIndex:0];
UIImage *image = [dict objectForKey:IQMediaImage];
NSMutableDictionary *dictParam = [[NSMutableDictionary alloc] init];
[dictParam setValue:imageData forKey:@"Files"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:@BaseURL(@"/MediaUpload") parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) ];
AFNetworking 3.0
【问题讨论】:
【参考方案1】:从AFURLSessionManager
查看这个方法:
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
完整代码实现:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
[[sessionManager uploadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@BaseURL(@"/MediaUpload")]]
fromFile:[NSURL fileURLWithPath:@"/path/to/uploading_file"]
progress:^(NSProgress * _Nonnull uploadProgress)
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error)
] resume];
【讨论】:
【参考方案2】:AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"multipart/formdata" forHTTPHeaderField:@"Content-Type"];
[manager POST:[NSString stringWithFormat:@"%@/api/1.0/customer/sign-up", DEFAULT_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
if (userHaveImage == YES)
[formData appendPartWithFileData:image name:@"img_profile" fileName:@"profileImage.jpg" mimeType:@"image/jpg"];
[formData appendPartWithFormData:image name:@"img_profile"];
然后将图像转换为 UTF8 字符串并以该格式发送。
【讨论】:
你的回答是对的。但我问我们可以直接传递图像吗?无需转换数据。或者没有传递图像 URL。以上是关于使用 AFNetworking 上传多个图像或文件,的主要内容,如果未能解决你的问题,请参考以下文章