废话不多说直接上网络请求工具类的代码
网络请求工具类 头文件.h 文件中:
/**
上传多张图片
@param path 路径
@param params 参数
@param images 图片数组
@param success success description
@param failure failure description
@param progress progress description
*/
+ (void)uploadMoreImagesWithPath:(NSString *)path
params:(NSDictionary *)params
images:(NSArray *)images
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure
progress:(HttpUploadProgressBlock)progress;
网络请求工具类 实现文件.m 文件中:
+ (void)uploadMoreImagesWithPath:(NSString *)path
params:(NSDictionary *)params
images:(NSArray *)images
success:(HttpSuccessBlock)success
failure:(HttpFailureBlock)failure
progress:(HttpUploadProgressBlock)progress {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// ContentType设置
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
manager.requestSerializer= [AFHTTPRequestSerializer serializer];
manager.responseSerializer= [AFHTTPResponseSerializer serializer];
// 上传完整地址
NSString * urlString = [URL_main stringByAppendingPathComponent:path];
[manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//把image 转为data , POST上传只能传data
// 1) 取当前系统时间
NSDate *date = [NSDate date];
// 2) 使用日期格式化工具
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
// 3) 指定日期格式
[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateStr = [formatter stringFromDate:date];
for (int i = 0; i < images.count; i++) {
UIImage *image = images[i];
NSData * pngImageData = UIImagePNGRepresentation(image);
// 4) 使用系统时间生成一个文件名
NSString *fileName = [NSString stringWithFormat:@"%@%d.png", dateStr,i + 1];
[formData appendPartWithFileData:pngImageData name:@"file" fileName:NSStringFormat(@"%@gauge.png",fileName) mimeType:@"image/png"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
// 上传进度
progress(uploadProgress.fractionCompleted);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"上传成功%@",responseObject);
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"上传失败%@",error);
failure(error);
}];
}
上传单张图片原理同上,只需要将 .m 文件中的 for 循环改为单张的即可
NSData * pngImageData = UIImagePNGRepresentation(image);
NSString *fileName = [NSString stringWithFormat:@"%@.png", dateStr];
[formData appendPartWithFileData:pngImageData name:@"file" fileName:NSStringFormat(@"%@gauge.png",fileName) mimeType:@"image/png"];