AFN:使用AFN实现文件上传

Posted on 2016-07-21 16:21  柠檬片  阅读(172)  评论(0)    收藏  举报
 1 -(void)upload2
 2 {
 3     //1.创建会话管理者
 4     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 5     
 6 //    NSDictionary *dictM = @{}
 7     //2.发送post请求上传文件
 8     /*
 9      第一个参数:请求路径
10      第二个参数:字典(非文件参数)
11      第三个参数:constructingBodyWithBlock 处理要上传的文件数据
12      第四个参数:进度回调
13      第五个参数:成功回调 responseObject:响应体信息
14      第六个参数:失败回调
15      */
16     [manager POST:@"http://120.25.226.186:32812/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
17         
18         UIImage *image = [UIImage imageNamed:@"Snip20160227_128"];
19         NSData *imageData = UIImagePNGRepresentation(image);
20         
21         //使用formData来拼接数据
22         /*
23          第一个参数:二进制数据 要上传的文件参数
24          第二个参数:服务器规定的
25          第三个参数:该文件上传到服务器以什么名称保存
26          */
27         //[formData appendPartWithFileData:imageData name:@"file" fileName:@"xxxx.png" mimeType:@"image/png"];
28         
29         //[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/Snip20160227_128.png"] name:@"file" fileName:@"123.png" mimeType:@"image/png" error:nil];
30         
31         [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/Snip20160227_128.png"] name:@"file" error:nil];
32 
33         
34     } progress:^(NSProgress * _Nonnull uploadProgress) {
35         
36         NSLog(@"%f",1.0 * uploadProgress.completedUnitCount/uploadProgress.totalUnitCount);
37         
38     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
39         NSLog(@"上传成功---%@",responseObject);
40         
41     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
42         NSLog(@"上传失败---%@",error);
43     }];
44     
45 }
文件上传