iOS利用AFNetworking实现文件上传的示例代码
0.导入框架准备工作
1.将框架程序拖拽进项目
2. 添加iOS框架引用
–SystemConfiguration.framework –MobileCoreServices.framework
3. 引入
#import"AFNetworking.h"
4.修改xxx-Prefix.pch文件
#import<MobileCoreServices/MobileCoreServices.h> #import<SystemConfiguration/SystemConfiguration.h>
1.AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理
@interfaceViewController()
{
//AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理
AFHTTPClient*_httpClient;
NSOperationQueue*_queue;
}
-(void)viewDidLoad
{
[superviewDidLoad];
NSURL*url=[NSURLURLWithString:@"http://192.168.3.255/~apple/qingche"];
_httpClient=[[AFHTTPClientalloc]initWithBaseURL:url];
_queue=[[NSOperationQueuealloc]init];
}
2.利用AFN实现文件上传操作细节
#pragmamark-文件上传
-(IBAction)uploadImage
{
/*
此段代码如果需要修改,可以调整的位置
1.把upload.php改成网站开发人员告知的地址
2.把file改成网站开发人员告知的字段名
*/
//1.httpClient->url
//2.上传请求POST
NSURLRequest*request=[_httpClientmultipartFormRequestWithMethod:@"POST"path:@"upload.php"parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData>formData){
//在此位置生成一个要上传的数据体
//form对应的是html文件中的表单
UIImage*image=[UIImageimageNamed:@"头像1"];
NSData*data=UIImagePNGRepresentation(image);
//在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
//要解决此问题,
//可以在上传时使用当前的系统事件作为文件名
NSDateFormatter*formatter=[[NSDateFormatteralloc]init];
//设置时间格式
formatter.dateFormat=@"yyyyMMddHHmmss";
NSString*str=[formatterstringFromDate:[NSDatedate]];
NSString*fileName=[NSStringstringWithFormat:@"%@.png",str];
/*
此方法参数
1.要上传的[二进制数据]
2.对应网站上[upload.php中]处理文件的[字段"file"]
3.要保存在服务器上的[文件名]
4.上传文件的[mimeType]
*/
[formDataappendPartWithFileData:dataname:@"file"fileName:fileNamemimeType:@"image/png"];
}];
//3.operation包装的urlconnetion
AFHTTPRequestOperation*op=[[AFHTTPRequestOperationalloc]initWithRequest:request];
[opsetCompletionBlockWithSuccess:^(AFHTTPRequestOperation*operation,idresponseObject){
NSLog(@"上传完成");
}failure:^(AFHTTPRequestOperation*operation,NSError*error){
NSLog(@"上传失败->%@",error);
}];
//执行
[_httpClient.operationQueueaddOperation:op];
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。