+ (void)uploadImages:(NSArray<UIImage *> *)images needOBJResults:(BOOL)needOBJResults complete:(void (^)(NSArray *imgUrls, NSArray *objArray, NSError *error))complete
{
NSDictionary *dict = @{@"userId":3333333};
// NSString *url = @"http://58.215.170.182:9090/api/upload/form/images";
NSString *url = [NSString stringWithFormat:@"%@/api/upload/form/images",@"http://www.baidu.com"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSString *timeStr = [NSString stringWithFormat:@"%@",@([[NSDate new] timeIntervalSince1970])];
for (int i = 0; i<images.count; i++) {
UIImage *image = images[i];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSString *name = [NSString stringWithFormat:@"%@_%@",timeStr,@(i)];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg",name];
[formData appendPartWithFileData:imageData name:@"pics" fileName:fileName mimeType:@"image/jpeg"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *dataResult = [responseObject hq_JSONObject];
NSError *error;
NSArray *imgUrls = @[];
NSArray *objArray = @[];
if ([dataResult isKindOfClass:[NSDictionary class]]) {
BOOL isSucess = [[dataResult hq_safeObjectForKey:@"success"] boolValue];
if (isSucess) {
NSDictionary *result = [dataResult hq_safeObjectForKey:@"data"];
if ([result isKindOfClass:[NSDictionary class]]) {
imgUrls = [result hq_safeObjectForKey:@"imageUrls"];
if (needOBJResults) {
objArray = [self imgObjArray:imgUrls images:images];
}
}
}
else {
error = [NSError errorWithDomain:@"上传图片失败" code:-1 userInfo:@{}];
}
}
if (complete) {
complete(imgUrls, objArray, error);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (complete) {
complete(@[], @[], error);
}
}];
}
+ (NSArray *)imgObjArray:(NSArray *)urlArray images:(NSArray *)images
{
NSMutableArray *objArray = [NSMutableArray new];
for (NSString *url in urlArray) {
NSRange range = [url rangeOfString:@"_"];
NSString *idxStr = [url substringFromIndex:range.location + 1];
NSRange jpgRange = [idxStr rangeOfString:@".jpg"];
idxStr = [idxStr substringToIndex:jpgRange.location];
NSInteger idx = [idxStr integerValue];
if (idx < images.count) {
UIImage *img = images[idx];
UploadImageOBJResults *obj = [UploadImageOBJResults new];
obj.url = url ? url : @"";
obj.width = img.size.width;
obj.height = img.size.height;
[objArray addObject:obj];
}
}
return [objArray copy];
}
Content-Type:multipart/form-data
抓包:
如上图,pass 是自定义参数, pics: xxxxxx.jpg 就是formData 里面的name 和fileName 以及mineType
[formData appendPartWithFileData:imageData name:@"pics" fileName:fileName mimeType:@"image/jpeg"];