iOS开发之使用AFN上传图片
Posted 李洪强
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
- }];
以上是关于iOS开发之使用AFN上传图片的主要内容,如果未能解决你的问题,请参考以下文章