iOS开发之使用AFN上传图片
- //1.创建管理者对象
- AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
- manager.responseSerializer = [AFJSONResponseSerializer serializer];
- manager.requestSerializer = [AFJSONRequestSerializer serializer];
- //2.上传文件
- NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"userHeader.png", @"userHeader", nil 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 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);
- }];