[置顶] iOS使用AFN上传单张、多张图片

时间:2022-08-29 08:10:37

iOS在上传图片时,AFN专门封装了一个上传文件的方法,但是这里需要特别强调的是name和mineType

[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d",i+1] fileName:[NSString stringWithFormat:@"file%d.jpg/png",i+1] mimeType:@"image/jpeg"]; 

name:服务器后台文件名的key,后台会根据这个字段获取相应的图片字节流

data: 需要上传的二进制数据

fileName:文件名带上后缀

mineType:文件类型

方法调用:

+ (void)uploadImagesWithImages:(NSArray<UIImage *> *)imageArray url:(NSString *)urlStr Parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
[manager POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
int imageCount = 0;
for (UIImage *image in imageArray) {
NSString *mineType = @"image/jpeg";
NSString *str =@"";
if (UIImagePNGRepresentation(image)) {
mineType = @"image/png";
str = @"png";
}else {
mineType = @"image/jpeg";
str = @"jpeg";
}
NSData *data = UIImageJPEGRepresentation(image, 0.30);
[formData appendPartWithFileData:data name:[NSString stringWithFormat:@"file%d",imageCount] fileName:[NSString stringWithFormat:@"icon%d.%@",imageCount,str] mimeType:mineType];
imageCount++;
}
} progress:^(NSProgress * _Nonnull uploadProgress) {

} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}