码迷,mamicode.com
首页 > 移动开发 > 详细

[iOS 多线程 & 网络 - 2.5] - 小文件上传

时间:2015-01-29 01:18:20      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:

A.文件上传
思路:
发送文件数据给服务器
使用post请求
必须手动设置请求头: 内容大小Content-Length & 内容类型 Content-Type
请求体:文件数据
文件上传的格式要求十分严格,必须严格遵守
由于是一次性加载文件到内存上传,所以只能用于小文件上传
 
B.实现
1.设置POST请求
(1)使用POST请求方法
(2)设置请求头
设置内容长度、内容类型、分割线
 
(3)设置请求体
NSMutableData *body = [NSMutableData data];
分割线 + 换行
内容描述 + 换行
内容类型 + 换行
换行
文件二进制数据 + 换行
分割线--
 
 
multipart/form-data 中的内容
技术分享
 
 
例如使用chrome上传一张图片:
技术分享
 
(4)使用本地请求获取某种文件类型的MIMEType
 1 /** 取得本地文件的MIMEType */
 2 - (void) getMIMEType {
 3     // Socket 实现断点上传
 4    
 5     //apache-tomcat-6.0.41/conf/web.xml 查找 文件的 mimeType
 6     //    UIImage *image = [UIImage imageNamed:@"test"];
 7     //    NSData *filedata = UIImagePNGRepresentation(image);
 8     //    [self upload:@"file" filename:@"test.png" mimeType:@"image/png" data:filedata parmas:@{@"username" : @"123"}];
 9    
10     // 给本地文件发送一个请求
11     NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil];
12     NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
13     NSURLResponse *repsonse = nil;
14     NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil];
15    
16     // 得到mimeType
17     NSLog(@"%@", repsonse.MIMEType);
18     [self upload:@"file" filename:@"itcast.txt" mimeType:repsonse.MIMEType data:data parmas:@{@"username":@"tom", @"type":@"xml"}];
19 }
 
 
附:常见文件类型的MIMEType
技术分享
 
  1 //
  2 //  ViewController.m
  3 //  UploadFileDemo
  4 //
  5 //  Created by hellovoidworld on 15/1/28.
  6 //  Copyright (c) 2015年 hellovoidworld. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 
 11 #define UTF8Encode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
 12 
 13 @interface ViewController ()
 14 
 15 - (IBAction)upload;
 16 
 17 @end
 18 
 19 @implementation ViewController
 20 
 21 - (void)viewDidLoad {
 22     [super viewDidLoad];
 23     // Do any additional setup after loading the view, typically from a nib.
 24 }
 25 
 26 - (void)didReceiveMemoryWarning {
 27     [super didReceiveMemoryWarning];
 28     // Dispose of any resources that can be recreated.
 29 }
 30 
 31 - (IBAction)upload {
 32     UIImage *image = [UIImage imageNamed:@"IMG_0413"];
 33     NSData *imageData = UIImagePNGRepresentation(image);
 34     [self upload:@"uploadedFile" filename:@"IMG_0413.PNG" mimeType:@"image/png" data:imageData parmas:nil];
 35 }
 36 
 37 - (void)upload:(NSString *)name filename:(NSString *)filename mimeType:(NSString *)mimeType data:(NSData *)data parmas:(NSDictionary *)params
 38 {
 39     // 文件上传
 40     NSURL *url = [NSURL URLWithString:@"http://192.168.0.21:8080/MyTestServer/upload"];
 41     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
 42     request.HTTPMethod = @"POST";
 43    
 44     // 设置请求体
 45     NSMutableData *body = [NSMutableData data];
 46    
 47     /***************文件参数***************/
 48     // 参数开始的标志
 49     [body appendData:UTF8Encode(@"--HelloVoidWorldBoundary\r\n")];
 50     // name : 指定参数名(必须跟服务器端保持一致)
 51     // filename : 文件名
 52     NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename];
 53     [body appendData:UTF8Encode(disposition)];
 54     NSString *type = [NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType];
 55     [body appendData:UTF8Encode(type)];
 56    
 57     [body appendData:UTF8Encode(@"\r\n")];
 58     [body appendData:data];
 59     [body appendData:UTF8Encode(@"\r\n")];
 60    
 61     /***************普通参数***************/
 62     [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
 63         // 参数开始的标志
 64         [body appendData:UTF8Encode(@"--HelloVoidWorldBoundary\r\n")];
 65         NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", key];
 66         [body appendData:UTF8Encode(disposition)];
 67        
 68         [body appendData:UTF8Encode(@"\r\n")];
 69         [body appendData:UTF8Encode(obj)];
 70         [body appendData:UTF8Encode(@"\r\n")];
 71     }];
 72    
 73     /***************参数结束***************/
 74     // HelloVoidWorldBoundary--\r\n
 75     [body appendData:UTF8Encode(@"--HelloVoidWorldBoundary--\r\n")];
 76     request.HTTPBody = body;
 77    
 78     // 设置请求头
 79     // 请求体的长度
 80     [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
 81     // 声明这个POST请求是个文件上传
 82     [request setValue:@"multipart/form-data; boundary=HelloVoidWorldBoundary" forHTTPHeaderField:@"Content-Type"];
 83    
 84     // 发送请求
 85     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
 86         NSLog(@"开始上传~~~");
 87         if (data) {
 88             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
 89             NSLog(@"%@", dict);
 90         } else {
 91             NSLog(@"上传失败");
 92         }
 93     }];
 94 }
 95 
 96 /** 取得本地文件的MIMEType */
 97 - (void) getMIMEType {
 98     // Socket 实现断点上传
 99    
100     //apache-tomcat-6.0.41/conf/web.xml 查找 文件的 mimeType
101     //    UIImage *image = [UIImage imageNamed:@"test"];
102     //    NSData *filedata = UIImagePNGRepresentation(image);
103     //    [self upload:@"file" filename:@"test.png" mimeType:@"image/png" data:filedata parmas:@{@"username" : @"123"}];
104    
105     // 给本地文件发送一个请求
106     NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil];
107     NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
108     NSURLResponse *repsonse = nil;
109     NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil];
110    
111     // 得到mimeType
112     NSLog(@"%@", repsonse.MIMEType);
113     [self upload:@"file" filename:@"itcast.txt" mimeType:repsonse.MIMEType data:data parmas:@{@"username":@"tom", @"type":@"xml"}];
114 }
115 
116 
117 @end
 
 
 
 

[iOS 多线程 & 网络 - 2.5] - 小文件上传

标签:

原文地址:http://www.cnblogs.com/hellovoidworld/p/4257682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!