IOS使用AFNetworking对图片服务器上传

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];

}

原文地址:https://www.cnblogs.com/lybandly521/p/5104885.html