nasMixUploadManager.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. //
  2. // nasMixUploadManager.m
  3. // 双子星云手机
  4. //
  5. // Created by xd h on 2024/8/27.
  6. //
  7. #import "nasMixUploadManager.h"
  8. #import "customUploadOperation.h"
  9. #import "nasUploadFileManager.h"
  10. #import "frpFileExistModel.h"
  11. #import "frpUploadModel.h"
  12. #define Kboundary2 @"Boundaryhxd"
  13. @interface nasMixUploadManager ()<NSURLSessionDataDelegate>
  14. //排队等候下载的上传地址数组
  15. @property(nonatomic,strong) NSMutableArray *uploadWaitingUrlArr;
  16. //正在下载的上传地址数组
  17. @property(nonatomic,strong) NSMutableArray *uploadingOperationArr;
  18. @property(nonatomic,assign) NSInteger speedShowCount;//内网的情况 多少次才刷新一次
  19. @end
  20. @implementation nasMixUploadManager
  21. + (instancetype)shareManager {
  22. static nasMixUploadManager *_instance;
  23. static dispatch_once_t onceToken;
  24. dispatch_once(&onceToken, ^{
  25. _instance = [[self alloc] init];
  26. });
  27. return _instance;
  28. }
  29. - (instancetype)init {
  30. if (self = [super init]) {
  31. _maxUploadLoadCount = 2;
  32. if ([connectDeviceManager shareInstance].isPingOk)
  33. {
  34. _speedShowCount = 3;
  35. }
  36. else{
  37. _speedShowCount = 0;
  38. }
  39. //[self registeNotification];
  40. }
  41. return self;
  42. }
  43. /** 添加要上传的 模型 */
  44. - (void)addDownloadWithModels:(NSArray *)fileModels{
  45. for (uploadFileDataModel *model in fileModels) {
  46. BOOL needAddType = YES;
  47. //1. 排查上传中
  48. for (customUploadOperation *operationDoing in self.uploadingOperationArr) {
  49. if([operationDoing.fileModel.filename isEqualToString:model.filename]){
  50. needAddType = NO;
  51. break;
  52. }
  53. }
  54. //1. 排查等待下载
  55. for (uploadFileDataModel *waitModel in self.uploadWaitingUrlArr) {
  56. if([waitModel.filename isEqualToString:model.filename]){
  57. needAddType = NO;
  58. break;
  59. }
  60. }
  61. if(needAddType){
  62. [self.uploadWaitingUrlArr addObject:model];
  63. }
  64. }
  65. //启动上传
  66. [self beginUpload];
  67. }
  68. //在添加XX后 启动下载
  69. - (void)beginUpload
  70. {
  71. BOOL isCanUseCellular = [HWDataManager getBoolWithKey:stringKeyAddSn(Const_file_Transfe_canUse_Cellular_all)];
  72. if(!isCanUseCellular){//不允许流量上传
  73. //
  74. if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN){
  75. mainBlock(^{
  76. [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileSuspendAllNotification object:nil];
  77. [[iToast makeText:NSLocalizedString(@"File_Transfer_By_Cellular_tip",nil)] show];
  78. });
  79. return;
  80. }
  81. }
  82. if(ksharedAppDelegate.DisabledFileTransferType){
  83. if(ksharedAppDelegate.isImageNewFor130){
  84. [[iToast makeText:NSLocalizedString(@"File_Transfer_Disable_tip",nil)] show];
  85. }
  86. else{
  87. [[iToast makeText:NSLocalizedString(@"File_Transfer_Disable_tip2",nil)] show];
  88. }
  89. return;
  90. }
  91. @synchronized (self) {
  92. if(self.uploadingOperationArr.count == _maxUploadLoadCount){
  93. HLog(@"正在上传的数量达到了最大值 %ld",_maxUploadLoadCount)
  94. return;
  95. }
  96. if(self.uploadWaitingUrlArr.count == 0){
  97. HLog(@"没有等待中的上传任务")
  98. return;
  99. }
  100. NSInteger canAddTaskNumber = _maxUploadLoadCount - self.uploadingOperationArr.count;
  101. for (int i=0; i<canAddTaskNumber; i++) {
  102. if(self.uploadWaitingUrlArr.count >= 1){
  103. //创建上传任务
  104. uploadFileDataModel *WaitingModel = self.uploadWaitingUrlArr.firstObject;
  105. __block customUploadOperation * operation = [customUploadOperation new];
  106. operation.fileModel = WaitingModel;
  107. //等待下载中的任务
  108. [self.uploadWaitingUrlArr removeObjectAtIndex:0];
  109. //添加到下载中数组
  110. [self.uploadingOperationArr addObject:operation];
  111. [self checkFileUploadStateWithOperation:operation];
  112. //[weakSelf handleTaskDidUploadWith:operation withState:state];
  113. }
  114. }
  115. }
  116. }
  117. #pragma mark 检测文件是否上传过了
  118. - (void)checkFileUploadStateWithOperation:(customUploadOperation*)operation
  119. {
  120. NSMutableDictionary*paraDict = [NSMutableDictionary new];
  121. if(operation.fileModel.savePath){
  122. NSString *absPath = [[NSString alloc] initWithFormat:@"%@%@",operation.fileModel.savePath,operation.fileModel.filename];
  123. [paraDict setValue:absPath forKey:@"absPath"];
  124. NSNumber *totalBytesNumber = [NSNumber numberWithLong:operation.fileModel.totalBytes];
  125. [paraDict setValue:totalBytesNumber forKey:@"fileSize"];
  126. }
  127. KWeakSelf
  128. [[netWorkManager shareInstance] cloudPhoneGETCallBackCode:@"isFileExist" Parameters:paraDict success:^(id _Nonnull responseObject) {
  129. frpFileExistModel *model = [[frpFileExistModel alloc] initWithDictionary:responseObject error:nil];
  130. if(model && model.status == 0){
  131. [weakSelf checkFileUploadStateFunAfterNetWith:model WithOperation:operation];
  132. }
  133. else{
  134. //FileExistRet(-1);
  135. }
  136. } failure:^(NSError * _Nonnull error) {
  137. HLog(@"%@",error)
  138. //FileExistRet(-1);
  139. }];
  140. }
  141. #pragma mark 检测分家是否存在后处理 是否要上传
  142. - (void)checkFileUploadStateFunAfterNetWith:(frpFileExistModel*)model WithOperation:(customUploadOperation*)operation
  143. {
  144. if(!model){
  145. return;
  146. }
  147. operation.fileModel.didUploadBytes = 0;
  148. operation.fileModel.taskId = model.data.taskId;
  149. if(!model.data.exist){//未上传过
  150. [self prepareToUploadFileWithOperation:operation];
  151. }
  152. else if(model.data.isComplete){//上传过了 并且文件上传完了
  153. //判断下文件创建长度是否一致 一致则是上传完了 不一致 重新上传一个 可能是同名的文件而已
  154. if(model.data.size >= operation.fileModel.totalBytes){//上传完了
  155. mainBlock(^{
  156. [[iToast makeText:NSLocalizedString(@"File_upload_file_already_exists",nil)] show];
  157. });
  158. NSMutableArray *delArr = [NSMutableArray new];
  159. [delArr addObject:operation.fileModel];
  160. [[nasUploadFileManager shareInstance] deleteUploadFileRecordBy:delArr withDelCache:YES complete:^(BOOL isSuccess) {
  161. if (isSuccess) {
  162. }
  163. }];
  164. }
  165. else{//未上传完 isComplete 这个字段有问题
  166. operation.fileModel.didUploadBytes = model.data.size;
  167. [self prepareToUploadFileWithOperation:operation];
  168. }
  169. }
  170. else{//上传过了 未上传完成
  171. operation.fileModel.didUploadBytes = model.data.size;
  172. [self prepareToUploadFileWithOperation:operation];
  173. }
  174. }
  175. #pragma mark 处理任务失败
  176. #pragma mark 准备上传文件
  177. - (void)prepareToUploadFileWithOperation:(customUploadOperation*)operation
  178. {
  179. NSMutableDictionary *paraDict = [NSMutableDictionary new];
  180. NSString* taskUid = operation.fileModel.taskId;
  181. if(!taskUid || taskUid.length == 0){
  182. taskUid = [iTools getTaskUidStr];
  183. operation.fileModel.taskId = taskUid;
  184. }
  185. [paraDict setObject:taskUid forKey:@"taskId"];
  186. [paraDict setObject:@0 forKey:@"position"];
  187. [paraDict setObject:@"true" forKey:@"isLast"];
  188. if(operation.fileModel.savePath){
  189. [paraDict setObject:operation.fileModel.savePath forKey:@"savePath"];
  190. }
  191. else{
  192. HLog(@"获取保存路径失败")
  193. return;
  194. }
  195. if(operation.fileModel.filename){
  196. [paraDict setObject:operation.fileModel.filename forKey:@"filename"];
  197. }
  198. else{
  199. HLog(@"获取用户名失败")
  200. return;
  201. }
  202. KWeakSelf
  203. if(operation.fileModel.curUploadFileType == uploadFileTypeImage){
  204. [paraDict setObject:@1 forKey:@"imageType"];
  205. if(!operation.fileModel.imageData){
  206. NSString*pathStr = [cachesFileManager getFilePathWithName:operation.fileModel.filename type:operation.fileModel.curUploadFileType];
  207. NSData *imageData = [NSData dataWithContentsOfFile:pathStr];
  208. if (!imageData) {
  209. if(!operation.fileModel.asset){
  210. NSString *curLocalIdentifier = operation.fileModel.localIdentifier;
  211. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[curLocalIdentifier] options:nil];
  212. PHAsset *asset = fetchResult.firstObject;
  213. operation.fileModel.asset = asset;
  214. }
  215. [[PHImageManager defaultManager] requestImageDataForAsset:operation.fileModel.asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
  216. // 直接得到最终的 NSData 数据
  217. if (imageData) {
  218. operation.fileModel.imageData = imageData;
  219. [weakSelf afterGetImageDataFunWithOperation:operation];
  220. }
  221. else{
  222. [weakSelf handleUploadFailOneFileBy:operation];
  223. }
  224. }];
  225. return;
  226. }
  227. operation.fileModel.imageData = imageData;
  228. }
  229. NSData *curData = operation.fileModel.imageData;
  230. operation.onceDataLengt = [curData length];
  231. [self startUpload:paraDict operation:operation data:curData success:^(id _Nonnull responseObject) {
  232. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:responseObject error:nil];
  233. if(model && model.position == operation.fileModel.totalBytes){
  234. HLog(@"%@上传完成 000",operation.fileModel.filename)
  235. [weakSelf handleUploadDoneOneFileBy:operation];
  236. }
  237. else{
  238. HLog(@"%@上传完成一片 %ld",operation.fileModel.filename,model.position)
  239. }
  240. } faild:^(NSError * _Nonnull error) {
  241. HLog(@"%@上传失败",operation.fileModel.filename)
  242. [weakSelf handleUploadFailOneFileBy:operation];
  243. }];
  244. }
  245. else{
  246. [paraDict setObject:@1 forKey:@"videoType"];
  247. [paraDict setObject:@"false" forKey:@"isLast"];
  248. if(![cachesFileManager checkFileIsSaveState:operation.fileModel.filename withType:uploadFileTypeVideo]){
  249. if(!operation.fileModel.asset){
  250. NSString *curLocalIdentifier = operation.fileModel.localIdentifier;
  251. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[curLocalIdentifier] options:nil];
  252. PHAsset *asset = fetchResult.firstObject;
  253. operation.fileModel.asset = asset;
  254. }
  255. //真正的视频数据
  256. PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
  257. options.version = PHVideoRequestOptionsVersionOriginal;
  258. [[PHImageManager defaultManager] requestAVAssetForVideo:operation.fileModel.asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  259. if ([asset isKindOfClass:[AVURLAsset class]]) {
  260. AVURLAsset* urlAsset = (AVURLAsset*)asset;
  261. BOOL isSuc = [cachesFileManager copyVideoItemAtPath:[urlAsset.URL path] fileName:operation.fileModel.filename error:nil];
  262. if (isSuc) {
  263. [weakSelf afterGetVideoDataFunWithOperation:operation];
  264. }
  265. else{
  266. [weakSelf handleUploadFailOneFileBy:operation];
  267. }
  268. }
  269. else{
  270. [weakSelf handleUploadFailOneFileBy:operation];
  271. }
  272. }];
  273. return;
  274. }
  275. long curPosition = operation.fileModel.didUploadBytes;
  276. [self beginUploadVideoDataFunBy:operation with:curPosition withPara:paraDict success:^(id _Nonnull responseObject) {
  277. } faild:^(NSError * _Nonnull error) {
  278. }];
  279. }
  280. }
  281. #pragma mark 视频上传
  282. - (void)beginUploadVideoDataFunBy:(customUploadOperation*)operation with:(NSInteger)position withPara:(NSMutableDictionary*)paraDict success:(netWork_Success)success faild:(netWork_Faild)faildStr
  283. {
  284. BOOL isLastPicece = NO;
  285. if((operation.fileModel.totalBytes - position) <= MaxNasUploadPieceSzie){
  286. [paraDict setObject:@"true" forKey:@"isLast"];
  287. isLastPicece = YES;
  288. }
  289. else{
  290. [paraDict setObject:@"false" forKey:@"isLast"];
  291. }
  292. [paraDict setObject:[NSNumber numberWithLong:position] forKey:@"position"];
  293. //视频数据切片
  294. __block NSData *videoData = [self cutVideoFileFunAtIndex:position withMaxLenght:MaxNasUploadPieceSzie withModel:operation.fileModel];
  295. if(!videoData ||videoData.length ==0){
  296. HLog(@"视频没获取到")
  297. [self handleUploadFailOneFileBy:operation];
  298. return;
  299. }
  300. operation.onceDataLengt = [videoData length];
  301. KWeakSelf
  302. [self startUpload:paraDict operation:operation data:videoData success:^(id _Nonnull responseObject) {
  303. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:responseObject error:nil];
  304. if(model && model.position >= operation.fileModel.totalBytes){
  305. HLog(@"%@上传完成 000",operation.fileModel.filename)
  306. [weakSelf handleUploadDoneOneFileBy:operation];
  307. }
  308. else{
  309. HLog(@"%@上传完成一片 %ld",operation.fileModel.filename,model.position)
  310. [weakSelf beginUploadVideoDataFunBy:operation with:model.position withPara:paraDict success:^(id _Nonnull responseObject) {
  311. success(responseObject);
  312. } faild:^(NSError * _Nonnull error) {
  313. NSError *err = error;
  314. if(error.code != -999){
  315. faildStr(err);
  316. }
  317. }];
  318. }
  319. } faild:^(NSError * _Nonnull error) {
  320. HLog(@"%@上传失败",operation.fileModel.filename)
  321. [weakSelf handleUploadFailOneFileBy:operation];
  322. }];
  323. }
  324. #pragma mark 分段读视频文件
  325. -(NSData*)cutVideoFileFunAtIndex:(NSUInteger)dataIndex withMaxLenght:(NSInteger)maxLengt withModel:(uploadFileDataModel*)dataModel{
  326. NSString *filePath = [cachesFileManager getFilePathWithName:dataModel.filename type:uploadFileTypeVideo]; // 文件路径
  327. NSFileManager *manager0 = [NSFileManager defaultManager];
  328. if(![manager0 fileExistsAtPath:filePath]) {
  329. return [NSData new];
  330. }
  331. NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; // 创建文件句柄
  332. // 设置分段读取的大小,这里以每次读取1KB为例
  333. const NSUInteger chunkSize = maxLengt;//cutVideoPieceSzie;//5 * 1024 *1024;
  334. NSMutableData *data = [NSMutableData data];
  335. if (fileHandle) {
  336. long long endOfFile = [fileHandle seekToEndOfFile];
  337. if(dataModel.totalBytes == 0
  338. || dataModel.totalBytes < endOfFile){//异常处理
  339. dataModel.totalBytes = endOfFile;
  340. }
  341. //异常处理
  342. if(endOfFile == dataIndex){
  343. dataModel.totalBytes = endOfFile;
  344. dataModel.didUploadBytes = endOfFile;
  345. dataModel.curUploadStateType = uploadStateDone;
  346. [fileHandle closeFile];
  347. return data;
  348. }
  349. if (endOfFile >= chunkSize) {
  350. // 读取文件的分段数据到某个位置
  351. [fileHandle seekToFileOffset:dataIndex];
  352. // 读取文件的分段数据
  353. NSData* chunk = [fileHandle readDataOfLength:chunkSize];
  354. if (chunk) {
  355. [data appendData:chunk];
  356. }
  357. }
  358. else{
  359. // 读取文件的分段数据到某个位置
  360. [fileHandle seekToFileOffset:dataIndex];
  361. [data appendData:[fileHandle readDataToEndOfFile]];
  362. }
  363. // 在这里可以对文件内容进行处理
  364. // ...
  365. // 关闭文件句柄
  366. [fileHandle closeFile];
  367. }
  368. HLog(@"视频切片完成 dataIndex:%ld --长度:%ld",dataIndex,[data length])
  369. return data;
  370. }
  371. #pragma mark 处理上传完成
  372. - (void)handleUploadDoneOneFileBy:(customUploadOperation*)operation
  373. {
  374. [[NSNotificationCenter defaultCenter] postNotificationName:nasUploadTaskExeEnd object:operation.fileModel];
  375. [_uploadingOperationArr removeObject:operation];
  376. [self beginUpload];
  377. }
  378. #pragma mark 处理删除失败
  379. - (void)handleUploadFailOneFileBy:(customUploadOperation*)operation
  380. {
  381. operation.fileModel.curUploadStateType = uploadStateFail;
  382. [[NSNotificationCenter defaultCenter] postNotificationName:nasUploadTaskExeError object:operation.fileModel];
  383. [_uploadingOperationArr removeObject:operation];
  384. [self beginUpload];
  385. }
  386. #pragma mark 根据 asset 获取到图片数据
  387. - (void)afterGetImageDataFunWithOperation:(customUploadOperation*)operation
  388. {
  389. [cachesFileManager getFileNameWithContent:operation.fileModel.imageData fileName:operation.fileModel.filename type:uploadFileTypeImage];
  390. [self prepareToUploadFileWithOperation:operation];
  391. }
  392. #pragma mark 根据 asset 获取到视频数据
  393. - (void)afterGetVideoDataFunWithOperation:(customUploadOperation*)operation
  394. {
  395. [self prepareToUploadFileWithOperation:operation];
  396. }
  397. #pragma mark 开始上传
  398. - (void)startUpload:(NSMutableDictionary *)params operation:(customUploadOperation*)operation data:(NSData *)data success:(netWork_Success)success faild:(netWork_Faild)faildStr {
  399. NSString *urlString = ksharedAppDelegate.NASFileByBoxService;
  400. urlString = [[NSString alloc] initWithFormat:@"%@uploadFile",urlString];
  401. NSURL *URL = [NSURL URLWithString:urlString];
  402. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  403. [request setHTTPMethod:@"POST"];
  404. //请求体
  405. NSMutableData *bodyData = [self getBodyDataWithRequest:request withModel:operation.fileModel withData:data withPara:params];
  406. //设置请求体
  407. [request setHTTPMethod:@"POST"];
  408. [request setHTTPBody:bodyData];
  409. //设置请求体长度
  410. NSInteger length = [bodyData length];
  411. [request setValue:[NSString stringWithFormat:@"%ld",length] forHTTPHeaderField:@"Content-Length"];
  412. //设置 POST请求文件上传
  413. [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary2] forHTTPHeaderField:@"Content-Type"];
  414. KWeakSelf
  415. //回话对象
  416. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
  417. operation.session = session;
  418. //请求task
  419. /*
  420. 第一个参数:请求对象
  421. 第二个参数:传递是要上传的数据(请求体)
  422. 第三个参数:
  423. */
  424. NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  425. //解析
  426. [weakSelf handleCustomUploadResultBy:data withResponse:response withError:error success:success faild:faildStr];
  427. }];
  428. // NSString *filePath = [cachesFileManager getFilePathWithName:dataModel.filename type:uploadFileTypeVideo]; // 文件路径
  429. // NSURL *filePathUrl = [NSURL URLWithString:filePath];
  430. //
  431. // NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:filePathUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  432. // HLog(@"data string:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
  433. //[weakSelf handleCustomUploadResultBy:data withResponse:response withError:error];
  434. // }];
  435. // NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  436. //
  437. // HLog(@"data string:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
  438. //[weakSelf handleCustomUploadResultBy:data withResponse:response withError:error];
  439. //
  440. //// NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
  441. //// NSDictionary *dict = (NSDictionary *)object;
  442. //// NSLog(@"=====%@",[dict objectForKey:@"success"]);
  443. // }];
  444. //执行Task
  445. [uploadTask resume];
  446. operation.dataTask = uploadTask;
  447. }
  448. #pragma mark 用系统方法写的上传处理
  449. - (void)handleCustomUploadResultBy:(NSData*)data withResponse:(NSURLResponse*)response withError:(NSError*)error success:(netWork_Success)success faild:(netWork_Faild)faildStr{
  450. if(error){
  451. HLog(@"上传错误:%@",error)
  452. if(error.code != -999){
  453. faildStr(error);
  454. }
  455. return;
  456. }
  457. NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
  458. NSDictionary *dict = (NSDictionary *)object;
  459. frpUploadModel *model = [[frpUploadModel alloc] initWithDictionary:dict error:nil];
  460. if(model && [model.msg isEqualToString:@"success"]){
  461. success(dict);
  462. }
  463. else{
  464. NSError *err = [NSError new];
  465. faildStr(err);
  466. }
  467. }
  468. - (NSMutableData *)getBodyDataWithRequest:(NSMutableURLRequest *)request withModel:(uploadFileDataModel*)dataModel withData:(NSData*)data withPara:(NSMutableDictionary*)params{
  469. //1 边界符号要配置请求头里面去
  470. /*
  471. multipart/form-data 是表单格式
  472. charset=utf-8 是utf-8编码
  473. bounary 是表单开头
  474. */
  475. [request setValue:[NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", Kboundary2] forHTTPHeaderField:@"Content-Type"];
  476. /// body
  477. NSMutableData *boydData = [NSMutableData data];
  478. // 2.1 边界符号(开始边界)
  479. //2.1.1 其它参数
  480. NSMutableString *paraString = [NSMutableString new];
  481. //[paraString appendFormat:@"--%@\r\n",Kboundary];//\n:换行 \n:切换到行首
  482. for (NSString *key in params) {
  483. NSString *value = params[key];
  484. [paraString appendFormat:@"--%@\r\n",Kboundary2];//\n:换行 \n:切换到行首
  485. [paraString appendFormat:@"Content-Disposition: form-data; name=\"%@\"",key];
  486. [paraString appendFormat:@"\r\n"];
  487. [paraString appendFormat:@"\r\n"];
  488. [paraString appendFormat:@"%@\r\n",value];
  489. }
  490. //[boydData appendData:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
  491. // body每一个段内容以换行符作为结束标示
  492. NSString *fileBeginBoundary = [NSString stringWithFormat:@"--%@\r\n", Kboundary2];
  493. //[boydData appendData:[fileBeginBoundary dataUsingEncoding:NSUTF8StringEncoding]];
  494. [paraString appendString:fileBeginBoundary];
  495. // 2.2 属性配置 名字;key;类型
  496. NSString *serverFileKey = @"image"; //key
  497. //NSString *serverFileKey = @"file";
  498. NSString *serverContentTypes = @"image/png"; //类型
  499. if (dataModel.curUploadFileType == uploadFileTypeVideo) {
  500. serverFileKey = @"video";
  501. serverContentTypes = @"video/mp4";
  502. }
  503. NSString *serverFileName = dataModel.filename; //name
  504. // filename已命名文件; name相当于一个key, 这个名字和服务器保持一致
  505. /*
  506. 理解key,表单发送给服务端,服务端拿到数据之后,可以将任务解析成一个字典了imageDict;图片数据会通过这个字典里面的name来获取图片(伪代码 image = imageDict[serverFileKey])
  507. */
  508. //2.3 拼接数据(创建一个字符串来拼装)
  509. NSMutableString *string = [NSMutableString new];
  510. [string appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\" ", @"file", serverFileName];
  511. //[string appendFormat:@"%@", KNewLine];
  512. [string appendFormat:@"\r\n"];
  513. [string appendFormat:@"Content-Type:%@", serverContentTypes];
  514. // [string appendFormat:@"%@", KNewLine];
  515. // [string appendFormat:@"%@", KNewLine];
  516. [string appendFormat:@"\r\n"];
  517. [string appendFormat:@"\r\n"];
  518. // [boydData appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];
  519. [paraString appendString:string];
  520. [boydData appendData:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
  521. // 2.3 拼接数据(拼接文件数据)
  522. [boydData appendData:data];
  523. // 2.4 边界符号 (结束边界)
  524. NSString *fileEndBoundary = [NSString stringWithFormat:@"\r\n--%@--", Kboundary2];
  525. [boydData appendData:[fileEndBoundary dataUsingEncoding:NSUTF8StringEncoding]];
  526. return boydData;
  527. }
  528. #pragma mark 上传的文件已存在
  529. - (void)handleTaskDidUploadWith:(customUploadOperation*)operation withState:(NSInteger)state
  530. {
  531. if(state == 1){
  532. [[iToast makeText:NSLocalizedString(@"File_upload_file_already_exists",nil)] show];
  533. }
  534. [self.uploadingOperationArr removeObject:operation];
  535. NSMutableArray *delArr = [NSMutableArray new];
  536. [delArr addObject:operation.fileModel];
  537. [[nasUploadFileManager shareInstance] deleteUploadFileRecordBy:delArr withDelCache:NO complete:^(BOOL isSuccess) {
  538. if (isSuccess) {
  539. }
  540. }];
  541. [self beginUpload];
  542. }
  543. #pragma mark - <NSURLSessionDataDelegate>
  544. // ssl 服务 证书信任
  545. - (void)URLSession:(NSURLSession *)session
  546. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  547. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
  548. if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
  549. return;
  550. }
  551. // 信任该插件
  552. NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
  553. // 第一个参数 告诉系统如何处置
  554. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  555. }
  556. //当请求协议是https的时候回调用该方法
  557. //Challenge 挑战 质询(受保护空间)
  558. //NSURLAuthenticationMethodServerTrust 服务器信任证书
  559. - (void)URLSession:(NSURLSession *)session
  560. task:(NSURLSessionTask *)task
  561. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  562. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {
  563. if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
  564. return;
  565. }
  566. // 信任该插件
  567. NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
  568. // 第一个参数 告诉系统如何处置
  569. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  570. }
  571. // 接受到响应调用
  572. - (void)URLSession:(NSURLSession *)session
  573. dataTask:(NSURLSessionDataTask *)dataTask
  574. didReceiveResponse:(NSURLResponse *)response
  575. completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
  576. completionHandler(NSURLSessionResponseAllow);
  577. }
  578. // 上传进度
  579. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
  580. //每包发送的大小bytesSent,totalBytesSent已经上传了多少;totalBytesExpectedToSend总共要发送多少
  581. // 32768 = 32KB
  582. HLog(@"didSendBodyData: %lld--%lld-%lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
  583. for (customUploadOperation*operation in _uploadingOperationArr) {
  584. if(operation.dataTask == task){
  585. operation.fileModel.didUploadBytes += bytesSent;
  586. //调整下大小 因为上传的数据 除了data 长度 还包含了 参数大小
  587. if(totalBytesSent == totalBytesExpectedToSend){
  588. operation.fileModel.didUploadBytes -= (totalBytesExpectedToSend - operation.onceDataLengt);
  589. }
  590. operation.i ++;
  591. if(operation.i >= _speedShowCount){
  592. [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileRefreshNotification object:operation.fileModel];
  593. operation.i = 0;
  594. }
  595. break;
  596. }
  597. }
  598. }
  599. #pragma mark 取消单个任务
  600. - (void)cancelUploadTaskFunWith:(uploadFileDataModel*)fileModel
  601. {
  602. @synchronized (self) {
  603. for (uploadFileDataModel*waitModel in _uploadWaitingUrlArr) {
  604. if([waitModel.filename isEqualToString:fileModel.filename]){
  605. [_uploadWaitingUrlArr removeObject:waitModel];
  606. return;
  607. }
  608. }
  609. for (customUploadOperation*operation in _uploadingOperationArr) {
  610. if([operation.fileModel.filename isEqualToString:fileModel.filename]){
  611. [operation.dataTask cancel];
  612. [_uploadingOperationArr removeObject:operation];
  613. [self beginUpload];
  614. break;
  615. }
  616. }
  617. }
  618. }
  619. #pragma mark 取消所有任务
  620. - (void)cancelUploadAllTaskFun
  621. {
  622. @synchronized (self) {
  623. [_uploadWaitingUrlArr removeAllObjects];
  624. for (customUploadOperation*operation in _uploadingOperationArr) {
  625. [operation.dataTask cancel];
  626. }
  627. [_uploadingOperationArr removeAllObjects];
  628. }
  629. }
  630. #pragma mark - lazy load
  631. - (NSMutableArray *)uploadWaitingUrlArr {
  632. if (!_uploadWaitingUrlArr) {
  633. _uploadWaitingUrlArr = [NSMutableArray array];
  634. }
  635. return _uploadWaitingUrlArr;
  636. }
  637. - (NSMutableArray *)uploadingOperationArr {
  638. if (!_uploadingOperationArr) {
  639. _uploadingOperationArr = [NSMutableArray array];
  640. }
  641. return _uploadingOperationArr;
  642. }
  643. @end