使用AFNetworking进行图片上传
转载自:http://blog.csdn.net/a645258072/article/details/51728806
项目中,我们经常会用到上传图片的功能,而目前的上传图片分为两种(我只知道两种,哈哈哈),一种是以将图片加密转成字符串的形式,另一种是以文件流的形式进行上传。记得去年12月份在网上随便找了一下,可能是我太low,找了好久没找到。本来早就想总结一下,可是呢...我吧...懒得看AFNetworking源码,就一直搁置了,今天工作做完了,正好分享一下。
第一种方式:文件流方式进行上传
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//接收类型不一致请替换一致text/html或别的
manager.responseSerializer.acceptableContentTypes = [NSSetsetWithObjects:@"application/json",
@"text/html",
@"image/jpeg",
@"image/png",
@"application/octet-stream",
@"text/json",
nil];
NSURLSessionDataTask *task = [managerPOST:url parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData> _NonnullformData) {
NSData *imageData =UIImageJPEGRepresentation(image,1);
NSDateFormatter *formatter = [[NSDateFormatteralloc] init];
formatter.dateFormat =@"yyyyMMddHHmmss";
NSString *str = [formatterstringFromDate:[NSDatedate]];
NSString *fileName = [NSStringstringWithFormat:@"%@.jpg", str];
//上传的参数(上传图片,以文件流的格式)
[formData appendPartWithFileData:imageData
name:@"file"
fileName:fileName
mimeType:@"image/jpeg"];
} progress:^(NSProgress *_Nonnull uploadProgress) {
//打印下上传进度
} success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
//上传成功
+ (NSString *)imageBase64WithDataURL:(UIImage *)image
{
NSData *imageData =nil;
NSString *mimeType =nil;
//图片要压缩的比例,此处100根据需求,自行设置
CGFloat x =100 / image.size.height;
if (x >1)
{
x = 1.0;
}
imageData = UIImageJPEGRepresentation(image, x);
mimeType = @"image/jpeg";
return [NSStringstringWithFormat:@"data:%@;base64,%@", mimeType,
[imageData base64EncodedStringWithOptions:0]];
}