首页 > 代码库 > iOS开发之使用AFN上传图片
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);
- }];
二、多张图片
[objc] view plain copy
- //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上传图片
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。