IOS afn三方上传图片

来源:互联网 发布:如何删除mac自带软件 编辑:程序博客网 时间:2024/04/29 04:02

时间 2014-01-01 16:47:00 博客园-原创精华区
原文  http://www.cnblogs.com/qingche/p/3500726.html

 官方建议AFN的使用方法

 1. 定义一个全局的AFHttpClient:包含有

    1> baseURL

    2> 请求

    3> 操作队列 NSOperationQueue

 2. 由AFHTTPRequestOperation负责所有的网络操作请求

 3. 修改xxx-Prefix.pch文件

#import <MobileCoreServices/MobileCoreServices.h>

#import <SystemConfiguration/SystemConfiguration.h>

0.导入框架准备工作

•1. 将框架程序拖拽进项目

•2.  添加iOS框架引用

–SystemConfiguration.framework

–MobileCoreServices.framework

•3.  引入

#import "AFNetworking.h"

1.AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理

 1 @interfaceViewController () 2  3 { 4  5     // AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理 6  7     AFHTTPClient    *_httpClient;17     NSOperationQueue *_queue;18 19 }
1 - (void)viewDidLoad2 {3     [super viewDidLoad];4     5     NSURL *url = [NSURL URLWithString:@"http://192.168.3.255/~apple/qingche"];6     _httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];7     8     _queue = [[NSOperationQueue alloc] init];9 }

2.利用AFN实现文件上传操作细节

 1 #pragma mark - 文件上传 2 - (IBAction)uploadImage 3 { 4     /* 5      此段代码如果需要修改,可以调整的位置 6       7      1. 把upload.php改成网站开发人员告知的地址 8      2. 把file改成网站开发人员告知的字段名 9      */10     // 1. httpClient->url11     12     // 2. 上传请求POST13     NSURLRequest *request = [_httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {14         // 在此位置生成一个要上传的数据体15         // form对应的是html文件中的表单16         17         18         UIImage *image = [UIImage imageNamed:@"头像1"];19         NSData *data = UIImagePNGRepresentation(image);20         21         // 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名22         // 要解决此问题,23         // 可以在上传时使用当前的系统事件作为文件名24         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];25         // 设置时间格式26         formatter.dateFormat = @"yyyyMMddHHmmss";27         NSString *str = [formatter stringFromDate:[NSDate date]];28         NSString *fileName = [NSString stringWithFormat:@"%@.png", str];29         30         31         /*32          此方法参数33          1. 要上传的[二进制数据]34          2. 对应网站上[upload.php中]处理文件的[字段"file"]35          3. 要保存在服务器上的[文件名]36          4. 上传文件的[mimeType]37          */38         [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];39     }];40     41     // 3. operation包装的urlconnetion42     AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];43     44     [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {45         NSLog(@"上传完成");46     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {47         NSLog(@"上传失败->%@", error);48     }];49     50     //执行51     [_httpClient.operationQueue addOperation:op];
0 0