POST上传文件之分类抽取——以后只需要把分类导入,使用NSMutableURLRequest的分类即可
2015-10-28 15:32
381 查看
每次上传文件拼接数据都很麻烦,为了解决这个问题。我们可以为NSMutableURLRequest抽取一个分类如下所示:
NSMutableURLRequest+Multipart.h
在控制器使用如下:
NSMutableURLRequest+Multipart.h
// // NSMutableURLRequest+Multipart.h // 06-POST上传 // // Created by apple on 15/1/20. // Copyright (c) 2015年 apple. All rights reserved. // #import <UIKit/UIKit.h> @interface NSMutableURLRequest (Multipart) /** url: 要上传的服务器的地址 loaclFilePath: 要上传的文件的全路径 fileName:保存到服务器的文件名 */ + (instancetype)requestWithURL:(NSURL *)url andLoaclFilePath:(NSString *)loaclFilePath andFileName:(NSString *)fileName; @endNSMutableURLRequest+Multipart.m
// // NSMutableURLRequest+Multipart.m // 06-POST上传 // // Created by apple on 15/1/20. // Copyright (c) 2015年 apple. All rights reserved. // #import "NSMutableURLRequest+Multipart.h" /**随便的字符串作为分隔符*/ static NSString *boundary = @"itcastupload"; @implementation NSMutableURLRequest (Multipart) + (instancetype)requestWithURL:(NSURL *)url andLoaclFilePath:(NSString *)loaclFilePath andFileName:(NSString *)fileName { // 2. post请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:2.0f]; // 2.1 指定post方法 request.HTTPMethod = @"POST"; // 2.2 拼接数据体 NSMutableData *dataM = [NSMutableData data]; // 1. \r\n--(可以随便写, 但是不能有中文)\r\n NSString *str = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary]; [dataM appendData:[str dataUsingEncoding:NSUTF8StringEncoding]]; // 2. Content-Disposition: form-data; name="userfile(php脚本中用来读取文件的字段)"; filename="demo.json(要保存到服务器的文件名)" str = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\" \r\n", fileName]; [dataM appendData:[str dataUsingEncoding:NSUTF8StringEncoding]]; // 3. Content-Type: application/octet-stream(上传文件的类型)\r\n\r\n str = @"Content-Type: application/octet-stream\r\n\r\n"; [dataM appendData:[str dataUsingEncoding:NSUTF8StringEncoding]]; // 4. 要上传的文件的二进制流 // 要上传图片的二进制 [dataM appendData:[NSData dataWithContentsOfFile:loaclFilePath]]; // 5. \r\n--(可以随便写, 但是不能有中文)--\r\n str = [NSString stringWithFormat:@"\r\n--%@--\r\n", boundary]; [dataM appendData:[str dataUsingEncoding:NSUTF8StringEncoding]]; // 2.4 设置请求体 request.HTTPBody = dataM; // 设置请求头 // Content-Length(文件的大小) 290 // Content-Type multipart/form-data; boundary(分隔符)=(可以随便写, 但是不能有中文) NSString *headerStr = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:headerStr forHTTPHeaderField:@"Content-Type"]; return request; } @end
在控制器使用如下:
// // ViewController.m // 06-POST上传 // // Created by apple on 15/1/20. // Copyright (c) 2015年 apple. All rights reserved. // #import "ViewController.h" #import "NSMutableURLRequest+Multipart.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self postUpLoad]; } - (void)postUpLoad { // 1. url NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/post/upload.php"]; // 2. post请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url andLoaclFilePath:[[NSBundle mainBundle] pathForResource:@"001.png" ofType:nil] andFileName:@"123456.png"]; // 3. 连接 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 反序列化处理 id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; NSLog(@"result = %@", result); }]; } @end
相关文章推荐
- java.lang.IllegalArgumentException: Page directive: invalid value for import
- 智能车上位机与下位机通信的例子
- iOS UICollectionView reloadData后找到某个cell 更新某个cell数据
- 基于xcodebuild和xcrun的自动化打包
- UIViewContentMode各类型效果
- U3D UGUI学习2 - RectTransform
- 可扩展的事件复用技术:epoll和kqueue
- iOS界面编程-UIPageControl
- Android Bluetooth蓝牙开发(一)
- Hql语句之uniqueResult()-hql只返回一个结果
- QuickSand图片点击后分裂成几份消失效果《IT蓝豹》
- iOS开发使用storyboard预览UI在不同屏幕显示效果
- Gradle Plugin User Guide
- Unable to convert MySQL date/time value to System.DateTime
- Xoreax IncrediBuild 安装使用
- Daikon Forge GUI Library(dfgui)之界面文字显示异常
- UITableViewCell的分割线不满屏的解决办法
- UITextField
- FragmentTabHost切换Fragment时避免重复加载UI
- Codeforces Round #250 (Div. 1) D. The Child and Sequence 线段树 区间取摸