MMFileUploadUtil.m 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. //
  2. // MMFileUploadUtil.m
  3. // RichTextEditDemo
  4. //
  5. // Created by aron on 2017/7/23.
  6. // Copyright © 2017年 aron. All rights reserved.
  7. //
  8. #import "MMFileUploadUtil.h"
  9. #import <UIKit/UIKit.h>
  10. //分隔符
  11. #define Boundary @"1a2b3c"
  12. //一般换行
  13. #define Wrap1 @"\r\n"
  14. //key-value换行
  15. #define Wrap2 @"\r\n\r\n"
  16. //开始分割
  17. #define StartBoundary [NSString stringWithFormat:@"--%@%@",Boundary,Wrap1]
  18. //文件分割完成
  19. #define EndBody [NSString stringWithFormat:@"--%@--",Boundary]
  20. @interface MMFileUploadUtil () <NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate>
  21. @property (strong,nonatomic) NSURLSession * session;
  22. @property (nonatomic, strong) NSMutableArray* uploadingItems;
  23. @property (nonatomic, strong) NSMutableDictionary* uploadingTaskIDToUploadItemMap;
  24. @property (nonatomic, strong) NSMutableArray* todoItems;
  25. @property (nonatomic, assign) NSInteger maxUploadTask;
  26. @end
  27. @implementation MMFileUploadUtil
  28. DEF_SINGLETON
  29. - (instancetype)init
  30. {
  31. self = [super init];
  32. if (self) {
  33. [self defaultConfig];
  34. }
  35. return self;
  36. }
  37. #pragma mark - ......::::::: public :::::::......
  38. - (void)uploadFileWithData:(NSData*)uploadData {
  39. NSMutableURLRequest * request = [self TSuploadTaskRequest];
  40. NSData* totalData = [self TSuploadTaskRequestBody:uploadData];
  41. NSURLSessionUploadTask * uploadtask = [self.session uploadTaskWithRequest:request fromData:totalData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  42. NSString* result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  43. // NSLog(@"completionHandler %@", result);
  44. }];
  45. [uploadtask resume];
  46. }
  47. - (void)addUploadItem:(id<UploadItemProtocal, UploadItemCallBackProtocal>)uploadItem {
  48. [self.todoItems addObject:uploadItem];
  49. [self startNextUploadTask];
  50. }
  51. - (void)removeUploadItem:(id<UploadItemProtocal, UploadItemCallBackProtocal>)uploadItem {
  52. }
  53. #pragma mark - ......::::::: private :::::::......
  54. - (NSMutableArray *)uploadingItems {
  55. if (!_uploadingItems) {
  56. _uploadingItems = [NSMutableArray array];
  57. }
  58. return _uploadingItems;
  59. }
  60. - (NSMutableArray *)todoItems {
  61. if (!_todoItems) {
  62. _todoItems = [NSMutableArray array];
  63. }
  64. return _todoItems;
  65. }
  66. -(NSMutableDictionary *)uploadingTaskIDToUploadItemMap {
  67. if (!_uploadingTaskIDToUploadItemMap) {
  68. _uploadingTaskIDToUploadItemMap = [[NSMutableDictionary alloc] init];
  69. }
  70. return _uploadingTaskIDToUploadItemMap;
  71. }
  72. - (NSURLSession *)session {
  73. if (!_session) {
  74. NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  75. _session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  76. }
  77. return _session;
  78. }
  79. - (void)startNextUploadTask {
  80. if (self.uploadingItems.count < _maxUploadTask) {
  81. // 添加下一个任务
  82. if (self.todoItems.count > 0) {
  83. id<UploadItemProtocal, UploadItemCallBackProtocal> uploadItem = self.todoItems.firstObject;
  84. [self.uploadingItems addObject:uploadItem];
  85. [self.todoItems removeObject:uploadItem];
  86. [self beginUploadItem:uploadItem];
  87. }
  88. }
  89. }
  90. - (void)beginUploadItem:(id<UploadItemProtocal, UploadItemCallBackProtocal>)uploadItem {
  91. NSMutableURLRequest * request = [self TSuploadTaskRequest];
  92. NSData* uploadData = [uploadItem mm_uploadData];
  93. NSData* totalData = [self TSuploadTaskRequestBody:uploadData];
  94. __block NSURLSessionUploadTask * uploadtask = nil;
  95. uploadtask = [self.session uploadTaskWithRequest:request fromData:totalData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  96. NSString* result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  97. // NSLog(@"completionHandler %@", result);
  98. if (nil == error) {
  99. NSString* imgUrlString = @"";
  100. if (data) {
  101. NSError *JSONSerializationError;
  102. id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&JSONSerializationError];
  103. if ([obj isKindOfClass:[NSDictionary class]]) {
  104. imgUrlString = [obj objectForKey:@"url"];
  105. }
  106. }
  107. // 成功回调
  108. // FIXME: ZYT uploadtask ???
  109. id<UploadItemProtocal, UploadItemCallBackProtocal> uploadItem = [self.uploadingTaskIDToUploadItemMap objectForKey:@(uploadtask.taskIdentifier)];
  110. if (uploadItem) {
  111. if ([uploadItem respondsToSelector:@selector(mm_uploadDone:)]) {
  112. [uploadItem mm_uploadDone:imgUrlString];
  113. }
  114. [self.uploadingTaskIDToUploadItemMap removeObjectForKey:@(uploadtask.taskIdentifier)];
  115. [self.uploadingItems removeObject:uploadItem];
  116. }
  117. } else {
  118. id<UploadItemProtocal, UploadItemCallBackProtocal> uploadItem = [self.uploadingTaskIDToUploadItemMap objectForKey:@(uploadtask.taskIdentifier)];
  119. if (uploadItem) {
  120. if ([uploadItem respondsToSelector:@selector(mm_uploadFailed)]) {
  121. [uploadItem mm_uploadFailed];
  122. }
  123. [self.uploadingTaskIDToUploadItemMap removeObjectForKey:@(uploadtask.taskIdentifier)];
  124. [self.uploadingItems removeObject:uploadItem];
  125. }
  126. }
  127. [self startNextUploadTask];
  128. }];
  129. [uploadtask resume];
  130. // 添加到映射中
  131. [self.uploadingTaskIDToUploadItemMap setObject:uploadItem forKey:@(uploadtask.taskIdentifier)];
  132. }
  133. - (void)defaultConfig {
  134. _maxUploadTask = 5;
  135. }
  136. /**
  137. 上传请求配置bodyData
  138. */
  139. -(NSData*)TSuploadTaskRequestBody:(NSData*)uploadData {
  140. NSMutableData* totlData=[NSMutableData new];
  141. NSDictionary* dictionary=@{@"name":@"testname",
  142. @"APPversion":@"3.2.3",
  143. @"serverIp":@"127.0.0.1",
  144. @"clientType":@"2"};
  145. NSArray* allKeys=[dictionary allKeys];
  146. for (int i=0; i<allKeys.count; i++) {
  147. NSString *disposition = [NSString stringWithFormat:@"%@Content-Disposition: form-data; name=\"%@\"%@",StartBoundary,allKeys[i],Wrap2];
  148. NSString* object=[dictionary objectForKey:allKeys[i]];
  149. disposition =[disposition stringByAppendingString:object];
  150. disposition =[disposition stringByAppendingString:Wrap1];
  151. // NSLog(@"%s\n%@",__FUNCTION__,disposition);
  152. [totlData appendData:[disposition dataUsingEncoding:NSUTF8StringEncoding]];
  153. }
  154. NSString *body=[NSString stringWithFormat:@"%@Content-Disposition: form-data; name=\"picture\"; filename=\"%@\";Content-Type:image/png%@",StartBoundary,@"demo_avatar_cook.png",Wrap2];
  155. [totlData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
  156. [totlData appendData:uploadData];
  157. [totlData appendData:[Wrap1 dataUsingEncoding:NSUTF8StringEncoding]];
  158. [totlData appendData:[EndBody dataUsingEncoding:NSUTF8StringEncoding]];
  159. return totlData;
  160. }
  161. /**
  162. 上传请求配置
  163. */
  164. -(NSMutableURLRequest*)TSuploadTaskRequest {
  165. NSString* uploadURLString = @"http://localhost:8080/JspJavaBeanDemo/servlet/UploadHandleServlet";
  166. NSMutableURLRequest* request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:uploadURLString]];
  167. request.HTTPMethod=@"POST";
  168. [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",Boundary] forHTTPHeaderField:@"Content-Type"];
  169. return request;
  170. }
  171. #pragma mark - ......::::::: NSURLSessionDelegate :::::::......
  172. -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
  173. // NSLog(@"didCompleteWithError = %@",error.description);
  174. // 失败回调
  175. if (error) {
  176. id<UploadItemProtocal, UploadItemCallBackProtocal> uploadItem = [self.uploadingTaskIDToUploadItemMap objectForKey:@(task.taskIdentifier)];
  177. if (uploadItem) {
  178. if ([uploadItem respondsToSelector:@selector(mm_uploadFailed)]) {
  179. [uploadItem mm_uploadFailed];
  180. }
  181. [self.uploadingTaskIDToUploadItemMap removeObjectForKey:@(task.taskIdentifier)];
  182. [self.uploadingItems removeObject:uploadItem];
  183. }
  184. }
  185. [self startNextUploadTask];
  186. }
  187. -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
  188. // NSLog(@"bytesSent:%@-totalBytesSent:%@-totalBytesExpectedToSend:%@", @(bytesSent), @(totalBytesSent), @(totalBytesExpectedToSend));
  189. // 进度回调
  190. id<UploadItemProtocal, UploadItemCallBackProtocal> uploadItem = [self.uploadingTaskIDToUploadItemMap objectForKey:@(task.taskIdentifier)];
  191. if ([uploadItem respondsToSelector:@selector(mm_uploadProgress:)]) {
  192. [uploadItem mm_uploadProgress:(totalBytesSent * 1.0f/totalBytesExpectedToSend)];
  193. }
  194. }
  195. @end