版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/PianZhideNanRen/article/details/62421422
我们在项目里会经常遇到上传数据的情况比如更新头像、发布信息。大家可以在网络层写一个通用的上传方法。
实现这个方法最重要的是理解:
[formData appendPartWithFileData:<#(nonnull NSData *)#> name:<#(nonnull NSString *)#> fileName:<#(nonnull NSString *)#> mimeType:<#(nonnull NSString *)#>]
这个方法有四个参数:
FileData:图片数据(NSData)
name:图片标签(NSString)这个要说明一下,在上传多张图片的时候,name不能相同,否则只会上传第一张图片
fileName:这个是服务器下保存的图片名字,当然这个也是不能重复的,建议大家插入上传时候的时间
mimeType:这个是上传数据的类型,根据你上传的数据填写;
好,上代码
- (void)updateImageWithCallback:(void (^)(DDYResponse *))callback imageArray:(NSArray *)imageArray {
AFHTTPSessionManager *manager = [self retAFNetworkForOutTime:outTime];
NSLog(@"Request URL:%@\nExplain:%@\nData:%@",_service.url,_service.explain,self.dicParams);
[manager POST:_service.url parameters:self.dicParams constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//如果是多张图片上传,可以在此增加for循环
int i = 0;
for (UIImage *image in imageArray) {
NSData *imageData = UIImagePNGRepresentation(image);
NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
NSString *imagePath = [NSString stringWithFormat:@"%f.png", time];
NSString *imageName = [NSString stringWithFormat:@"headImage_%d", i];
i++;
//多张上传的时候name不能一样
[formData appendPartWithFileData:imageData
name:imageName
fileName:imagePath
mimeType:@"image/png"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"upload head image progress:%@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[SVProgressHUD dismiss];
NSError *error;
NSDictionary *dic = nil;
if ([responseObject isKindOfClass:[NSDictionary class]]) {
dic = responseObject;
}else{
dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
}
NSLog(@"图片上传成功:%@",dic);
DDYResponse* response = [DDYResponse new];
response.code = [dic[@"code"] intValue];
response.message = dic[@"msg"];
response.data = dic;
if (callback) {
callback(response);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"图片上传失败");
[SVProgressHUD dismiss];
DDYResponse* response = [DDYResponse new];
response.code = REQUEST_Error;
response.message = @"网络异常";
response.data = nil;
if (callback) {
callback(response);
}
NSLog(@"error:%@", error);
}];
}