当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS利用AFNetworking实现文件上传的示例代码

iOS利用AFNetworking实现文件上传的示例代码

2019年07月24日  | 移动技术网移动技术  | 我要评论

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
{
  [super viewdidload];
  
  nsurl *url = [nsurl urlwithstring:@"http://192.168.3.255/~apple/qingche"];
  _httpclient = [[afhttpclient alloc] initwithbaseurl:url];
  
  _queue = [[nsoperationqueue alloc] init];
}

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

#pragma mark - 文件上传
- (ibaction)uploadimage
{
  /*
   此段代码如果需要修改,可以调整的位置
   
   1. 把upload.php改成网站开发人员告知的地址
   2. 把file改成网站开发人员告知的字段名
   */
  // 1. httpclient->url
  
  // 2. 上传请求post
  nsurlrequest *request = [_httpclient multipartformrequestwithmethod:@"post" path:@"upload.php" parameters:nil constructingbodywithblock:^(id<afmultipartformdata> formdata) {
    // 在此位置生成一个要上传的数据体
    // form对应的是html文件中的表单
    
    
    uiimage *image = [uiimage imagenamed:@"头像1"];
    nsdata *data = uiimagepngrepresentation(image);
    
    // 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
    // 要解决此问题,
    // 可以在上传时使用当前的系统事件作为文件名
    nsdateformatter *formatter = [[nsdateformatter alloc] init];
    // 设置时间格式
    formatter.dateformat = @"yyyymmddhhmmss";
    nsstring *str = [formatter stringfromdate:[nsdate date]];
    nsstring *filename = [nsstring stringwithformat:@"%@.png", str];
    
    
    /*
     此方法参数
     1. 要上传的[二进制数据]
     2. 对应网站上[upload.php中]处理文件的[字段"file"]
     3. 要保存在服务器上的[文件名]
     4. 上传文件的[mimetype]
     */
    [formdata appendpartwithfiledata:data name:@"file" filename:filename mimetype:@"image/png"];
  }];
  
  // 3. operation包装的urlconnetion
  afhttprequestoperation *op = [[afhttprequestoperation alloc] initwithrequest:request];
  
  [op setcompletionblockwithsuccess:^(afhttprequestoperation *operation, id responseobject) {
    nslog(@"上传完成");
  } failure:^(afhttprequestoperation *operation, nserror *error) {
    nslog(@"上传失败->%@", error);
  }];
  
  //执行
  [_httpclient.operationqueue addoperation:op];

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网