使用post方法上传文件的两种做法
2015-07-28 15:58
337 查看
方法一,从0开始文件上传
NSURL *url = [NSURL URLWithString:@"http://yo.diveinedu.com/upload.php"];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];request.HTTPMethod = @"POST";//0. 设置分隔符NSString *boundary = @"a1b2c3d4e5f6";[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];NSLog(@"%@", request.allHTTPHeaderFields);NSMutableData *httpBody = [NSMutableData data];//1. 开始的分隔符[httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];//2. 设置内容: 标签名,文件名等[httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"%@\"\r\n", @"mask0.png"] dataUsingEncoding:NSUTF8StringEncoding]];NSString *path = [[NSBundle mainBundle] pathForResource:@"mask0" ofType:@"png"];NSLog(@"%@", [self typeForPath:path]);//3. 设置内容格式[httpBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", [self typeForPath:path]] dataUsingEncoding:NSUTF8StringEncoding]];NSString *body = [[NSString alloc] initWithData:httpBody encoding:NSUTF8StringEncoding];NSLog(@"%@", body);//4. 添加真正的内容NSData *data = [NSData dataWithContentsOfFile:path];[httpBody appendData:data];//5. 添加结束边界[httpBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];//6. 设置http bodyrequest.HTTPBody = httpBody;//7. 发送请求[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", str);}];重点:注意协议中需要使用回车换行(\r\n)的位置,HTTP是一个基于文本行的协议,通过回车换行来控制格式。
注意分隔符(Boundary)的设置,尤其是(--)的增加。
设置后的内容应该是下面的样子(为了看得更清楚,将回车换行用文字表示出来了):
POST /upload.php HTTP/1.1\r\nHost: yo.diveinedu.com\r\nContent-Type: multipart/form-data; boundary=abcdefghigk\r\n\r\nContent-Disposition: form-data; name="fileToUpload"; filename="mask0.png"\r\nContent-Type: image/png\r\n\r\n--abcdefghigk\r\n图片数据\r\n--abcdefghigk--\r\n
方法二,使用AFNetworking中的方法
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.responseSerializer = [AFHTTPResponseSerializer serializer];[manager POST:@"http://yo.diveinedu.com/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { //1. 方法一// NSError *error;// if (![formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"fileToUpload" fileName:[path lastPathComponent] mimeType:@"image/png" error:&error]) {// NSLog(@"error appending part: %@", error);// } //2. 方法二 NSData *data = [NSData dataWithContentsOfFile:path]; [formData appendPartWithFileData:data name:@"fileToUpload" fileName:[path lastPathComponent] mimeType:@"image/png"];} success:^(AFHTTPRequestOperation *operation, id responseObject) { NSData *data = (NSData *)responseObject; NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", str);} failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error);}];进行网络编程的时候,可以使用Wireshark之类的抓包工具辅助调试。可以很明确的看到发送或接收的数据是否正确。最后祝大家儿童节快乐~~~http://io.diveinedu.comhttp://www.diveinedu.comhttp://bbs.diveinedu.comhttps://github.com/DiveinEdu-CN
相关文章推荐
- C++第三节:二次删除、内存泄漏
- PageSwitch插件实现100种不同图片切换效果
- ASP.NET常见对象之Request与Response
- 树莓派ping主机名比IP地址慢的原因及解决方法
- cxf+spring实现ws-security的数字证书验证方式的记录(包括生成证书步骤)
- Navicat_V11.0.10 for Mysql(绿色免安装破解版)
- objc_msgSend()报错Too many arguments to function call ,expected 0,have3
- 如何构建职场软实力
- iOS开发-CGRect,CGSize结构体与NSString字符串互相转换
- 线段树+RMQ区间最值问题
- 遗传算法理解(通俗易懂)
- JSTL中<c:import />标签的简单使用-以和Spring MVC搭配为例
- 教程-最全ASCII 码对照表
- .net json数据序列化/反序列化
- iOS tableViewCell plane格式下,接近section边缘不显示分割线却被复用解决办法
- 217.Contains Duplicate(判断一个数组是否有重复数出现)
- 列式数据库
- 1.IOS TableView滑动显示多个按钮
- nginx配置404页面 <备忘>
- 【图论】【二分图匹配】[POJ 1325]Machine Schedule