一、上传图片
二、下载图片
一、上传图片
AFN 上传文件使用到了AFHTTPSessionManager
- 准备一张图片
- 转化为NSData
- 设置一个目录路径 path
- 把data 写入到路径里面
- 使用AFN上传
废话不多说 直接上代码
NSString*const requestURL =@"http://192.168.1.30/s/1/demo/index.php?s=/App&m=test&a=index&callback=true";
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];
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) {
session.responseSerializer=[AFHTTPResponseSerializerserializer];
[session POST:requestURLparameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData> _NonnullformData) {
//图片的路径
NSString*path = [NSStringstringWithFormat:@"%@",dic[@"image"]];
NSData *data = UIImagePNGRepresentation (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]]];
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);
{
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];
NSFileManager*fileManager = [NSFileManagerdefaultManager];
BOOL isFile = [fileManagerfileExistsAtPath:[filePathpath]];
if (isFile) {
//更新界面需要使用主线程
dispatch_async(dispatch_get_main_queue(), ^{
//设置图片视图的的图片
imageView.image= [UIImageimageWithContentsOfFile:[filePath path]];
});
}
}];
[download resume];
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];