之所以总结一下, 是因为网上搜到的写的并不太好, 特此整理一下, 包含单文件上传, 多文件并行上传, 多文件串行上传
传递格式
dictionary包含了name, filename, data 分别对应对象句柄变量名, 传递文件名, 传递文件二进制/本地url
全部使用multipart/form-data表单模拟上传
默认params都通过字典传递, 并且都使用post方式发送变量参数
单文件上传
我对其进行了少许修改, 如果发的data类型是nsdata或者是nsurl, 进入不同的api, 这里并没有特别的
+(NSURLSessionUploadTask*)uploadTaskUrl:(NSURL*)uploadPage params:(NSDictionary*)params file:(NSDictionary<NSString*,id>*)unitData completion:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock {
// 构造 NSURLRequest
NSLog(@"url %@\nparam %@",uploadPage,params);
NSError* error = NULL;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[uploadPage absoluteString] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (unitData && [unitData objectForKey:@"key"] && [unitData objectForKey:@"filename"] && [unitData objectForKey:@"data"]) {
if ([[unitData objectForKey:@"data"] isKindOfClass:[NSData class]]) {
[formData appendPartWithFileData:(NSData*)[unitData objectForKey:@"data"] name:[unitData objectForKey:@"key"] fileName:[unitData objectForKey:@"filename"] mimeType:@"multipart/form-data"];
}else if([[unitData objectForKey:@"data"] isKindOfClass:[NSURL class]]){
[formData appendPartWithFileURL:(NSURL*)[unitData objectForKey:@"data"] name:[unitData objectForKey:@"key"] fileName:[unitData objectForKey:@"filename"] mimeType:@"multipart/form-data" error:nil];
}
}
} error:&error];
NSLog(@"error %@",error);
// 可在此处配置验证信息
// 将 NSURLRequest 与 completionBlock 包装为 NSURLSessionUploadTask
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
} completionHandler:completionBlock];
return uploadTask;
}
多文件串行上传 (不推荐)
对接口进行多次调用, 每次只传一个文件, 通过线程控制序列, 缺点是返回多个结果, 因为是多次服务器交互访问, 这也是从网上找下来的, 网上可以搜到一大片, 关于多文件上传, 大概有2~3种这样做的方法, 个人认为既然官方支持append api, 那么就说明插入的数据是可以多重的, 也就有了并行上传的方法, 不需要再管进程的事更方便
+(void)uploadTasks:(NSURL*)uploadPage files:(NSArray<NSDictionary<NSString*,id>*>*)arrFiles progress:(void(^)(float progress))onProgress complete:(void(^)(NSArray<NSDictionary*>* result))onComplete error:(void(^)(NSError* error))onError{
// 需要上传的数据
// 准备保存结果的数组,元素个数与上传的图片个数相同,先用 NSNull 占位
NSMutableArray* result = [NSMutableArray array];
for (NSInteger i=arrFiles.count;i>0;i--) {
[result addObject:[NSNull null]];
}
dispatch_group_t group = dispatch_group_create();
for (NSInteger i = 0; i < arrFiles.count; i++) {
dispatch_group_enter(group);
NSURLSessionUploadTask* uploadTask = [self uploadTaskUrl:uploadPage params:@{} file:arrFiles[i] completion:^(NSURLResponse *response, NSDictionary* responseObject, NSError *error) {
onProgress((float)i/arrFiles.count);
if (error) {
NSLog(@"第 %d 张图片上传失败: %@", (int)i + 1, error);
onError(error);
dispatch_group_leave(group);
} else {
NSLog(@"第 %d 张图片上传成功: %@", (int)i + 1, responseObject);
@synchronized (result) { // NSMutableArray 是线程不安全的,所以加个同步锁
result[i] = responseObject;
}
dispatch_group_leave(group);
}
}];
[uploadTask resume];
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"上传完成!");
for (id response in result) {
NSLog(@"%@", response);
}
onComplete(result);
});
}
多文件并行上传 (推荐)
所谓并行上传, 也就是对同一个接口同时传递多个二进制文件/url, 因为有的时候是需要实现这一功能的, 同时上传多个文件但只需一次服务器访问
+(NSURLSessionUploadTask*)uploadTaskUrl:(NSURL*)uploadPage params:(NSDictionary*)params files:(NSArray<NSDictionary<NSString*,id>*>*)fileDatas completion:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock {
NSLog(@"url %@\nparam %@",uploadPage,params);
NSError* error = NULL;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[uploadPage absoluteString] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (int i=0; i<fileDatas.count; i++) {
NSDictionary* unitData = fileDatas[i];
if (unitData && [unitData objectForKey:@"key"] && [unitData objectForKey:@"filename"] && [unitData objectForKey:@"data"]) {
if ([[unitData objectForKey:@"data"] isKindOfClass:[NSData class]]) {
[formData appendPartWithFileData:(NSData*)[unitData objectForKey:@"data"] name:[unitData objectForKey:@"key"] fileName:[unitData objectForKey:@"filename"] mimeType:@"multipart/form-data"];
}else if([[unitData objectForKey:@"data"] isKindOfClass:[NSURL class]]){
[formData appendPartWithFileURL:(NSURL*)[unitData objectForKey:@"data"] name:[unitData objectForKey:@"key"] fileName:[unitData objectForKey:@"filename"] mimeType:@"multipart/form-data" error:nil];
}
}
}
} error:&error];
NSLog(@"error %@",error);
// 将 NSURLRequest 与 completionBlock 包装为 NSURLSessionUploadTask
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
} completionHandler:completionBlock];
return uploadTask;
}
喜欢就收藏个吧, 顺便投个币