nasMixUploadManager.m 31 KB

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