多文件带参数上传及多文件文本信息上传工具类的封装
来源:互联网 发布:淘宝客手机源码 编辑:程序博客网 时间:2024/06/06 01:21
下述代码包含了以下几个部分的封装:#pragma mark - 获取单例对象#pragma mark - 由于请求体是添加的二进制数据,故用nsdata作为返回值#pragma mark - 动态生成文件类型#pragma mark - POST请求上传文件带多个参数#pragma mark - 文件上传的封装: 采用 POST 请求#pragma mark - 多文件 + 文本信息 的上传#pragma mark - 多文件+文本信息 上传的封装***************************************** .h部分@interface SGHUnloadManager : NSObject/** * 单例:对象的生命周期不用管理 * * @return 返回的是一个单例对象 */+ (instancetype)shareManager;/** * 获取文件信息(文件类型/文件名称) * * @param filePath 文件路径 * * @return 封装好的文件路径调用 */- (NSURLResponse *)getFileTypeWithFilePath:(NSString *)filePath;/** * 单文件上传请求体数据格式封装 * * @param filePath 文件路径 * @param fileKey 服务器接收文件参数的 key 值 * @param fileName 文件在服务器保存的名称:若此值为nil,则使用系统建议的名称 * * @return 封装好的请求体数据 */- (NSData *)getHTTPBodyWithPath:(NSString *)filePath fileKey:(NSString *)fileKey fileName:(NSString *)fileName;/** * 多文件+文本信息 上传的封装 * * @param fileKey 服务器接收文件参数的 key 值. * @param fileDict 文件字典; key(文件在服务器中保存的名称) value(文件地址) * @param textDict 文本信息字典; key(服务器接收文本信息的key值) value(文本信息) * * @return 拼接好的请求体数据 */- (NSData *)getHTTPBodyWithFileKey:(NSString *)fileKey withFileDict:(NSDictionary *)fileDict textDict:(NSDictionary *)textDict;/** * 多文件 + 文本信息 的上传 * * @param urlString 上传文件的接口 * @param fileKey 服务器接收文件参数的 key 值 * @param fileDict 文件字典; key(文件在服务器中保存的名称) value(文件地址) * @param textDict 文本信息字典; key(服务器接收文本信息的key值) value(文本信息) */- (void)POSTUnloadFileWithUrlString:(NSString *)urlString withFileKey:(NSString *)fileKey withFileDict:(NSDictionary *)fileDict withTextDict:(NSDictionary *)textDict;/** * POST请求:上传文件带多个参数封装 * * @param urlString 上传文件的接口 * @param filePath 上传文件路径 * @param fileKey 服务器接收文件参数的 key 值 * @param fileName 文件在服务器保存的名称:若此值为nil,则使用系统建议的名称 */- (void)POSTUnloadFileWithUrlString:(NSString *)urlString withFilePath:(NSString *)filePath withFileKey:(NSString *)fileKey withFileName:(NSString *)fileName;/** * POST请求:上传文件带多个参数封装 * * @param urlString 上传文件的接口 * @param filePath 上传文件路径 * @param fileKey 服务器接收文件参数的 key 值 * @param fileName 文件在服务器保存的名称:若此值为nil,则使用系统建议的名称 * @param completionHandler 网络请求完之后的回调!直接拿的是系统的 Block 异步的网络上传,在主线程执行 Block 回调 内部是对 NSUrlSession 的封装 */- (void)POSTUnloadFileWithUrlString:(NSString *)urlString withFilePath:(NSString *)filePath withFileKey:(NSString *)fileKey withFileName:(NSString *)fileName completionHandler:(void(^ _Nonnull )(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;@end----------------------------------------------------- .m部分 #define kBoundary @"kBoundary"@implementation SGHUnloadManager<span style="color:#FF0000;">#pragma mark - 获取单例对象</span>+ (instancetype)shareManager{ static id _instance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[self alloc] init]; }); return _instance;}<span style="color:#FF0000;">#pragma mark - 由于请求体是添加的二进制数据,故用nsdata作为返回值</span>- (NSData *)getHTTPBodyWithPath:(NSString *)filePath fileKey:(NSString *)fileKey fileName:(NSString *)fileName{ //请求体内容 NSMutableData *data = [NSMutableData data]; //1.设置文件的上边界 NSMutableString *headerStr = [NSMutableString stringWithFormat:@"--%@\r\n",kBoundary]; NSURLResponse *responce = [self getFileTypeWithFilePath:filePath]; // MIMEType:就是需要的文件类型! NSString *fileType = responce.MIMEType; if (!fileName) { // suggestedFilename:建议的文件名称. fileName = responce.suggestedFilename; } //文件上边界的拼接 [headerStr appendFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n",fileKey,fileName]; // Content-Type: application/json :告诉服务器上传文件的类型! // 注意:两个换行! [headerStr appendFormat:@"Content-Type: %@\r\n\r\n",fileType]; [data appendData:[headerStr dataUsingEncoding:NSUTF8StringEncoding]]; //2.设置文件内容 [data appendData:[NSData dataWithContentsOfFile:filePath]]; //3. 将下边界拼接到请求体中 NSMutableString *footerStr = [NSMutableString stringWithFormat:@"\r\n--%@--\r\n",kBoundary]; [data appendData:[footerStr dataUsingEncoding:NSUTF8StringEncoding]]; return data; }<span style="color:#FF0000;">#pragma mark - 动态生成文件类型</span>- (NSURLResponse *)getFileTypeWithFilePath:(NSString *)filePath{ //1.发送一个请求,访问本地文件: file请求 //本地文件协议: ftp 协议 file:// NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@",filePath]]]; //2.初始化NSURLResponse // 相当于定义了一块空地址!利用这块空地址,来接收响应头和响应行信息! NSURLResponse *response = nil; // 同步方法:返回值,就是实体内容; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; NSLog(@"response--%@",response); return response; }<span style="color:#FF0000;">#pragma mark - POST请求上传文件带多个参数</span>- (void)POSTUnloadFileWithUrlString:(NSString *)urlString withFilePath:(NSString *)filePath withFileKey:(NSString *)fileKey withFileName:(NSString *)fileName{ [self POSTUnloadFileWithUrlString:urlString withFilePath:filePath withFileKey:fileKey withFileName:fileName completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { }];}<span style="color:#FF0000;">#pragma mark - 文件上传的封装: 采用 POST 请求</span>- (void)POSTUnloadFileWithUrlString:(NSString *)urlString withFilePath:(NSString *)filePath withFileKey:(NSString *)fileKey withFileName:(NSString *)fileName completionHandler:(void (^)(NSData * _Nullable, NSURLResponse * _Nullable, NSError * _Nullable))completionHandler{ //1.获取url NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //2。设置请求方法 request.HTTPMethod = @"POST"; //multipart/form-data; boundary=---------------------------18804770636611649421118790616 //3。设置文件上传类型,请求头 NSString *type = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",kBoundary]; [request setValue:type forHTTPHeaderField:@"Content-Type"]; //4.设置请求体 request.HTTPBody =[self getHTTPBodyWithPath:filePath fileKey:@"userfile" fileName:@"SNIP" ]; //5.发送请求 // 2.发送网络请求:异步请求. // Block :网络请求完成之后的异步回调! [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //网络完成之后的回调 dispatch_async(dispatch_get_main_queue(), ^{ //执行自己的block if (completionHandler) { //此block中执行的是最外界的内容 completionHandler(data,response,error); NSLog(@"2.执行Block中的内容!"); NSLog(@"------同步执行------%@",[NSThread currentThread]); } }); NSLog(@"data%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]resume]; }<span style="color:#FF0000;">#pragma mark - 多文件 + 文本信息 的上传</span>- (void)POSTUnloadFileWithUrlString:(NSString *)urlString withFileKey:(NSString *)fileKey withFileDict:(NSDictionary *)fileDict withTextDict:(NSDictionary *)textDict{ NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; NSString *type = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",kBoundary]; [request setValue:type forHTTPHeaderField:@"Content-Type"]; request.HTTPBody = [self getHTTPBodyWithFileKey:@"userfile[]" withFileDict:fileDict textDict:textDict]; [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"data---%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }); }] resume]; }<span style="color:#FF0000;">#pragma mark - 多文件+文本信息 上传的封装</span>- (NSData *)getHTTPBodyWithFileKey:(NSString *)fileKey withFileDict:(NSDictionary *)fileDict textDict:(NSDictionary *)textDict{ NSMutableData *data = [NSMutableData data]; // 上传文件的信息 在 fileDict 中. // 遍历文件字典,取出文件,拼接格式 [fileDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { // fileName :文件在服务器中保存的名称. // filePath :文件路径! NSString *filename = key; NSString *filepath = obj; NSURLResponse *response = [[SGHUnloadManager shareManager] getFileTypeWithFilePath:filepath]; NSString *fileType = response.MIMEType; //上传文件的上边界 NSMutableString *headerStr = [NSMutableString stringWithFormat:@"\r\n--%@\r\n",kBoundary]; [headerStr appendFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n",fileKey,filename]; [headerStr appendFormat:@"Content-Type: %@\r\n\r\n",fileType]; NSData *headerData = [headerStr dataUsingEncoding:NSUTF8StringEncoding]; [data appendData:headerData]; //拼接文件内容 NSData *fileData = [NSData dataWithContentsOfFile:filepath]; [data appendData:fileData]; }]; //普通文本信息参数 //遍历文本字典,并取出每一条数据进行数据拼接 [textDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { //textKey :服务器接收文本信息的 key 值 //text:文本信息 NSString *textKey = key; NSString *text = obj; //文本信息的上边界 NSMutableString *str = [NSMutableString stringWithFormat:@"\r\n--%@\r\n",kBoundary]; [str appendFormat:@"Content-Disposition: form-data; name=%@\r\n\r\n",textKey]; NSData *headerData = [str dataUsingEncoding:NSUTF8StringEncoding]; [data appendData:headerData]; //设置文本信息内容 NSData *textData = [text dataUsingEncoding:NSUTF8StringEncoding]; [data appendData:textData]; }]; //所有上传文件的下边界 NSMutableString *footerStr = [NSMutableString stringWithFormat:@"\r\n--%@--",kBoundary]; [data appendData:[footerStr dataUsingEncoding:NSUTF8StringEncoding]]; return data; }@end*****************************************************想使用的朋友可以参考以下代码,多多指教:#pragma mark - 当手指点击屏幕的时候调用- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ //将文件名及文件路径用字典包装起来 NSString *name1 = @"file1"; NSString *name2 = @"file2"; NSString *name3 = @"file3"; NSString *path1 = @"/Users/apple/Desktop/5217b8616a1cb42cf26d99e2cd5c465b.jpg"; NSString *path2 = @"/Users/apple/Desktop/e4522e16ae3dbfc6e2324a76769bf10d.jpg"; NSString *path3 = @"/Users/apple/Desktop/fc52d1043778da85ebc1767126067410.jpg"; NSDictionary *fileDict = @{name1:path1,name2:path2,name3:path3}; //设置文本字典 NSString *textKey1 = @"username"; NSString *value1 = @"shiguanghui"; NSString *textKey2 = @"age"; NSString *value2 = @"18"; NSString *textKey3 = @"ID"; NSString *value3 = @"1112403008"; NSDictionary *textDict = @{textKey1:value1,textKey2:value2,textKey3:value3}; [[SGHUnloadManager shareManager] POSTUnloadFileWithUrlString:@"http://localhost/upload/upload-m.php" withFileKey:@"userfile[]" withFileDict:fileDict withTextDict:textDict];}
0 0
- 多文件带参数上传及多文件文本信息上传工具类的封装
- springMVC上传多个文件带参数
- 带参数文件上传
- spring mvc上传带参数的文件
- 上传文件及参数
- 使用FileUpload上传文件封装工具类
- iOS开发 - 封装文件上传工具类
- 单文件上传工具类封装解析
- PHP实现单文件上传、多个单文件上传、多文件上传的过程化封装
- ajaxfileupload带参数上传文件
- ajaxfileupload带参数上传文件
- ajaxfileupload带参数上传文件
- okhttp 上传带参数文件
- Android文件上传带参数
- 封装的上传文件
- android 多文件上传封装
- 安卓下httppost多个文件的上传及参数
- 多文件上传带进度条的
- Head First Servlet&Jsp 学习笔记(一) 一些基础知识
- javascript变量声明提升(hoisting)
- Ubuntu Server安装图形界面
- PNChart,简洁高效有动画效果的iOS图表库
- POJ 2001 Shortest Prefixes
- 多文件带参数上传及多文件文本信息上传工具类的封装
- Python常用指令
- C语言中的高精度乘法
- CallbackMappingJackson2HttpMessageConverter(jsonp请求)
- Java IO框架
- 今天开始每天记录所学 请努力前行 请默默前行 不要被自己的感动。
- vbox虚拟机的couldn't resolve host问题
- 单例模式的两种方式:饿汉模式与懒汉模式
- 这次空的好