廢話不多說(shuō)直接上網(wǎng)絡(luò)請(qǐng)求工具類的代碼
網(wǎng)絡(luò)請(qǐng)求工具類 頭文件.h 文件中:
/**
上傳多張圖片
@param path 路徑
@param params 參數(shù)
@param images 圖片數(shù)組
@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;
網(wǎng)絡(luò)請(qǐng)求工具類 實(shí)現(xiàn)文件.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設(shè)置
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 轉(zhuǎn)為data , POST上傳只能傳data
// 1) 取當(dāng)前系統(tǒng)時(shí)間
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) 使用系統(tǒng)時(shí)間生成一個(gè)文件名
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) {
// 上傳進(jìn)度
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 循環(huán)改為單張的即可
NSData * pngImageData = UIImagePNGRepresentation(image);
NSString *fileName = [NSString stringWithFormat:@"%@.png", dateStr];
[formData appendPartWithFileData:pngImageData name:@"file" fileName:NSStringFormat(@"%@gauge.png",fileName) mimeType:@"image/png"];