iOS开发之使用AFN上传图片

时间:2022-08-29 08:11:07

一、单张图片

//1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

//2.上传文件
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"userHeader.png", @"userHeader", nil];
[manager POST:URL parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {

//上传文件参数
[formData appendPartWithFileData:data name:@"userHeader" fileName:@"userHeader.png" mimeType:@"image/jpeg"];

} progress:^(NSProgress * _Nonnull uploadProgress) {

//打印上传进度
CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
DLog(@"%.2lf%%", progress);

} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {

//请求成功
DLog(@"请求成功:%@",responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

//请求失败
DLog(@"请求失败:%@",error);

}];

二、多张图片

//1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

//2.上传文件
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"userHeader.png", @"userHeader", @"image.png", @"image", nil];
[manager POST:URL parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {

//上传文件参数
[formData appendPartWithFileData:data1 name:@"userHeader" fileName:@"userHeader.png" mimeType:@"image/jpeg"];
[formData appendPartWithFileData:data2 name:@"image" fileName:@"image.png" mimeType:@"image/jpeg"];

} progress:^(NSProgress * _Nonnull uploadProgress) {

//打印上传进度
CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
DLog(@"%.2lf%%", progress);

} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {

//请求成功
DLog(@"请求成功:%@",responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

//请求失败
DLog(@"请求失败:%@",error);

}];
注意:上传文件参数中的data、data1、data2都是图片转成的二进制流,比较简单,这里就不赘述了.