iOS 一次上传多张图片, 并返回进度值
Posted 心泪无恒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 一次上传多张图片, 并返回进度值相关的知识,希望对你有一定的参考价值。
我封装的使用AFNetworking上传多图的一个方法。带进度条回调,希望对你用帮助,我app中亲测可用,不知道你的服务器是如何接收数据的:
/** * 上传带图片的内容,允许多张图片上传(URL)POST * * @param url 网络请求地址 * @param images 要上传的图片数组(注意数组内容需是图片) * @param parameter 图片数组对应的参数 (注意多张图片,每张的图片名应该不同) * @param parameters 其他参数字典 * @param ratio 图片的压缩比例(0.0~1.0之间) * @param succeedBlock 成功的回调 * @param failedBlock 失败的回调 * @param uploadProgressBlock 上传进度的回调 */ +(void)startMultiPartUploadTaskWithURL:(NSString *)url imagesArray:(NSArray *)images parameterOfimages:(NSString *)parameter parametersDict:(NSDictionary *)parameters compressionRatio:(float)ratio succeedBlock:(void(^)(id operation, id responseObject))succeedBlock failedBlock:(void(^)(id operation, NSError *error))failedBlock uploadProgressBlock:(void(^)(float uploadPercent,long long totalBytesWritten,long long totalBytesExpectedToWrite))uploadProgressBlock; 实现: +(void)startMultiPartUploadTaskWithURL:(NSString *)url imagesArray:(NSArray *)images parameterOfimages:(NSString *)parameter parametersDict:(NSDictionary *)parameters compressionRatio:(float)ratio succeedBlock:(void (^)(id, id))succeedBlock failedBlock:(void (^)(id, NSError *))failedBlock uploadProgressBlock:(void (^)(float, long long, long long))uploadProgressBlock{ if (images.count == 0) { NSLog(@"上传内容没有包含图片"); return; } for (int i = 0; i < images.count; i++) { if (![images isKindOfClass:[UIImage class]]) { NSLog(@"images中第%d个元素不是UIImage对象",i+1); return; } } AFHTTPRequestOperation *operation = [[self sharedOperation].operationManager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { int i = 0; //根据当前系统时间生成图片名称 NSDate *date = [NSDate date]; NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; [formatter setDateFormat:@"yyyy年MM月dd日"]; NSString *dateString = [formatter stringFromDate:date]; for (UIImage *image in images) { NSString *fileName = [NSString stringWithFormat:@"%@%d.png",dateString,i]; NSData *imageData; if (ratio > 0.0f && ratio < 1.0f) { imageData = UIImageJPEGRepresentation(image, ratio); }else{ imageData = UIImageJPEGRepresentation(image, 1.0f); } [formData appendPartWithFileData:imageData name:parameter fileName:fileName mimeType:@"image/jpg/png/jpeg"]; } } success:^(AFHTTPRequestOperation *operation, id responseObject) { succeedBlock(operation,responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@",error); failedBlock(operation,error); }]; [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { CGFloat percent = totalBytesWritten * 1.0 / totalBytesExpectedToWrite; uploadProgressBlock(percent,totalBytesWritten,totalBytesExpectedToWrite); }]; }
以上是关于iOS 一次上传多张图片, 并返回进度值的主要内容,如果未能解决你的问题,请参考以下文章
js-jssdk微信H5选择多张图片预览并上传(兼容ios,安卓,已测试)