目前IOS端开发,图片上传到服务器分为两种,一种是直接上到服务器,一种是借助第三方储存(减少服务器压力)。
一、直接上传到服务器
/**
* 代码演示
*/
//*******UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的图片数据量大很多,但从视角角度看,图片的质量没有明显的降低,所以在读取图片数据内容时,可以先使用UIImageJPEGRepresentation,且耗时短。
//******将选中的图片压缩成二进制文件*******photo为UIImage实例
NSData *data = UIImageJPEGRepresentation(photo, 0.5);
//****** 从本地上传图片 先读入沙盒目录
//****** 创建沙盒目录
NSString *docomentpaths = [NSHomeDirectory() stringByAppendingPathComponent:@"docomentpaths"];
NSFileManager *manager = [NSFileManager defaultManager];
[manager createDirectoryAtPath:docomentpaths withIntermediateDirectories:YES attributes:nil error:nil];
//*****获取当前时间字符
NSString *timeStr = [NSString stringWithFormat:@"%@",[NSDate date]];
//*****读入沙盒目录下
[manager createFileAtPath:[docomentpaths stringByAppendingString:[NSString stringWithFormat:@"%@",timeStr]] contents:data attributes:nil];
//*****得到图片路径
NSString *filepath = [[NSString alloc]initWithFormat:@"%@%@",docomentpaths,timeStr];
//****** 得到本地的图片URL
NSURL *imageurl = [NSURL fileURLWithPath:filepath];
//****url服务器接口地址
//使用AFN网络框架上传
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];
[manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// 开始上传 formData提交
[formData appendPartWithFileURL:imageurl name:@"ios_uploadImage" fileName:filepath mimeType:@"image/jpeg" error:nil];
} // 这里上传多张图片for循环提交
// for (int i = 0; i<self.imagelist.count; i++)
// {
// [formData appendPartWithFileURL:self.iamgedata[i] name:@"heareuy" fileName:self.strlist[i] mimeType:@"image/jpeg" error:nil];
// }
// } success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) { } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) { }];
二、上传到第三方服务器存储-七牛云存储
原来公司的项目也是上传到公司服务器上,但想着图片量会很大,随着图片量的增多,后期也是一个问题,所以我决定使用七牛云作为图片存储盘,过程其实是非常简单的。后台的伙伴们会在七牛上注册,实例化一个盘,在手机端上传时,后台会给一个从七牛获取到token。根据这个token手机端会把图片上传到七牛,上传成功后,七牛会返回一个图片的url,然后再将这个url给服务器,说白了,服务器只是保存手机端上传到七牛的地址。
首先导入七牛云的SDK,拷贝七牛云给demo里面的方法.如下:
//********需要上传的图片
NSData *data = UIImageJPEGRepresentation(imag, 1.0f);
// ***********用时间戳来给图片命名
NSDateFormatter *formatter;
NSString *dateString;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyMMddhhmmss"];
dateString = [formatter stringFromDate:[NSDate date]];
dateString =[dateString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSString *token = @"从服务端SDK获取";
//******七牛云申请的域名
NSString *qiniuIP = @"http://oddgox1e4.bkt.clouddn.com/";
QNUploadManager *upManager = [[QNUploadManager alloc] init];
[upManager putData:data key:dateString token:token
complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
NSLog(@"info=%@", info);
NSLog(@"key=%@", key);
NSLog(@"resp=%@", resp);
[self uploadiamg:[NSString stringWithFormat:@"%@%@",qiniuIP,key]]; } option:nil];
uploadiamg:自己写上传服务器的方法。搞定。