AFNetworking实现多张图片上传
2016-09-14 本文已影响173人
MrLiangC
利用AFNetworking实现多张图片上传,比如要上传的参数是其他参数加一个图片数组如下:
- (void)sendComments {
//上传的参数如下:
NSDictionary *dic = @{@"eva.eva_goods_id":@(goodsId),
@"eva.eva_user_id":userId,
@"eva.eva_grade":@(_grade),
@"eva.eva_detail":commentText
@"photos":@[1.png,2.png]};
//这里我们需要将photos参数分离出来具体代码如下:
NSDictionary *paramsDict = @{@"eva.eva_goods_id":@(goodsId),
@"eva.eva_user_id":userId,
@"eva.eva_grade":@(_grade),
@"eva.eva_detail":commentText};
NSMutableArray *imageArray = [NSMutableArray array];
//这里假设_selectedPhotos是从本地相册选取的图片,具体实现这里将不作说明了
if (_selectedPhotos.count > 0 ) {
for (UIImage *image in _selectedPhotos) {
NSData *imagedata = [self imageDataWithImage:image];
[imageArray addObject:imagedata];
}
}
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:url parameters:paramsDict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
for (NSInteger i = 0; i < imageArray.count; i++) {
NSData *picData = uploadParamArray[i];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
//文件名
NSString *fileNmae = [NSString stringWithFormat:@"%@%ld.png",[formatter stringFromDate:[NSDate date]],(long)i];
//其中name需要设置为图片上传的参数名pothos, mimeType是文件的类型
[formData appendPartWithFileData:picData name:@"photo" fileName:fileNmae mimeType:@"image/png"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//上传成功后的回调
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//上传失败
}];
}
- (NSData *)imageDataWithImage:(UIImage *)image {
NSData *data;
if (UIImagePNGRepresentation(image) == nil) {
data = UIImageJPEGRepresentation(image, 1);
}else {
data = UIImageJPEGRepresentation(image, 0.01);
}
return data;
}