最近在写项目的时候项遇到到了图片上传的问题,在这里将所用到的方法记录下来。在这里用NSData数据流进行上传。
废话不多说直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| NSData * imageData = UIImageJPEGRepresentation(image, 0.1); AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil]; NSURLSessionDataTask *task = [manager POST:KReportImageUrl parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { NSData *imageDatas = imageData; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyyMMddHHmmss"; NSString *str = [formatter stringFromDate:[NSDate date]]; NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str]; //上传的参数(上传图片,以文件流的格式) [formData appendPartWithFileData:imageDatas name:@"photo" fileName:fileName mimeType:@"image/jpeg"]; } progress:^(NSProgress * _Nonnull uploadProgress) { //上传进度 NSLog(@"%@",uploadProgress); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //上传成功 NSLog(@"上传成功");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //上传失败 NSLog(@"上传失败========>%@",error); }];
|