使用AFN上传图片 下载图片

一、上传图片

二、下载图片


一、上传图片

AFN 上传文件使用到了AFHTTPSessionManager 

  1. 准备一张图片
  2. 转化为NSData 
  3. 设置一个目录路径 path  
  4. 把data 写入到路径里面
  5. 使用AFN上传


废话不多说 直接上代码



UIImage*image = [UIImageimageNamed:@"icon.png"];
   
NSData *data = UIImagePNGRepresentation(image);
   
   
NSString*path = [[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"icon.png"];
  
BOOL writer =  [data writeToFile:pathatomically:NO];

   
NSDictionary*dic =@{@"image":path};

   
   
AFHTTPSessionManager*session = [AFHTTPSessionManagermanager];
//这两项一定要设置否则会报一个 不正确的格式 的错误
    session.requestSerializer= [AFHTTPRequestSerializerserializer];
    session.
responseSerializer=[AFHTTPResponseSerializerserializer];
   
    [session
POST:requestURLparameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData_NonnullformData) {
       
//图片的路径
  NSString*path = [NSStringstringWithFormat:@"%@",dic[@"image"]];

      //转化为data

          UIImage *image = [ UIImage imageWithContentsOfFile :path];
       
NSData *data = UIImagePNGRepresentation (image);
//设置一个上传到服务器上文件的名字
       
NSDateFormatter*formatter = [[NSDateFormatteralloc]init];
        [formatter
setDateFormat:@"yyyy-MM-dd_HH-mm-ss"];
       
NSString*fileName =  [NSStringstringWithFormat:@"%@.png",[formatterstringFromDate:[NSDatedate]]];

  //name 是服务器上对应的名字  data 是要上传的图片  fileName 是上传到服务器上图片的名字  type 是文件的类型       
        [formData
appendPartWithFileData:dataname:@"fileData"fileName:fileNamemimeType:@"image/png"];
       
    }
progress:nilsuccess:^(NSURLSessionDataTask*_Nonnull task, id _Nullable responseObject) {
       
        
NSLog(@"success:%@",[[NSStringalloc]initWithData:responseObjectencoding:NSUTF8StringEncoding]);
    }
failure:^(NSURLSessionDataTask*_Nullable task, NSError* _Nonnull error) {
        
NSLog(@"error:%@",error.localizedDescription);
    }];



二、下载图片  

下载图片同样使用到了 AFHTTPSessionManager

不过需要注意的是 下载图片 AFN 返回了一个下载会话需要自己启动

NSURLSessionDownloadTask *download =   [session downloadTaskWithRequest :request progress : nil destination :^ NSURL * _Nonnull ( NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {};
  [download resume ];


直接上代码

NSString*constimageURLS = @"http://www.feizl.com/upload2007/2011_05/110505164429412.jpg";  //图片的网址

//先定义一个图片视图 一会下载完图片使用
 imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(100,100,100,100)];
    [self.viewaddSubview:imageView];
   imageView.backgroundColor= [UIColorgrayColor];

//调用下载
[selfdownloadImage];

- (void)downloadImage
{
   
AFHTTPSessionManager*session = [AFHTTPSessionManagermanager];
    session.
requestSerializer= [AFHTTPRequestSerializerserializer];
    session.
responseSerializer= [AFHTTPResponseSerializerserializer];
   
   
NSURLRequest*request = [NSURLRequestrequestWithURL:[NSURLURLWithString:imageURLS]];
   
 
NSURLSessionDownloadTask*download =   [session downloadTaskWithRequest:request progress:nildestination:^NSURL* _Nonnull(NSURL* _Nonnull targetPath, NSURLResponse * _Nonnull response) {
       
        
NSError*error = nil;
       
NSURL*URL = [[NSFileManagerdefaultManager]URLForDirectory:NSDocumentDirectoryinDomain:NSUserDomainMaskappropriateForURL:nilcreate:NOerror:&error];

       
//告诉服务器文件保存在哪
       
return[URL URLByAppendingPathComponent:[responsesuggestedFilename]isDirectory:NO];
       
    }
completionHandler:^(NSURLResponse* _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
          
NSLog(@"response:%@,filePath:%@,error%@",response,filePath,error.localizedDescription);
   
//判断目录里面是否存在这个图片
       
NSFileManager*fileManager = [NSFileManagerdefaultManager];
       BOOL isFile = [fileManagerfileExistsAtPath:[filePathpath]];
       if (isFile) {
  //更新界面需要使用主线程
           dispatch_async(dispatch_get_main_queue(), ^{
//设置图片视图的的图片
               
imageView.image= [UIImageimageWithContentsOfFile:[filePath path]];
            });
        }
    }];
    [download
resume];
}


我实现的只是简单的AFN 的上传 、下载。

图片的下载实际上还可以直接使用NSData 去加载网络图片

UIImageView *imagess = [[UIImageViewalloc]initWithFrame:CGRectMake(100,250, 100,100)];

    imagess.image = [UIImageimageWithData:[NSDatadataWithContentsOfURL:[NSURLURLWithString:@"http://img.taopic.com/uploads/allimg/121010/235039-12101011131311.jpg"]]];

    [self.viewaddSubview:imagess];






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值