转载:[IOS 多线程 & 网络 - 2.5] – 小文件上传
A.文件上传
思路:
发送文件数据给服务器
使用post请求
必须手动设置请求头: 内容大小Content-Length & 内容类型 Content-Type
请求体:文件数据
文件上传的格式要求十分严格,必须严格遵守
由于是一次性加载文件到内存上传,所以只能用于小文件上传
B.实现
1.设置POST请求
(1)使用POST请求方法
(2)设置请求头
设置内容长度、内容类型、分割线
(3)设置请求体
NSMutableData *body = [NSMutableData data];
分割线 + 换行
内容描述 + 换行
内容类型 + 换行
换行
文件二进制数据 + 换行
分割线–
multipart/form-data 中的内容
Image(46)
例如使用chrome上传一张图片:
5A66D35E-E958-49A9-AD92-9C54E4CCFA83
(4)使用本地请求获取某种文件类型的MIMEType
/** 取得本地文件的MIMEType */
- (void) getMIMEType {
// Socket 实现断点上传
//apache-tomcat-6.0.41/conf/web.xml 查找 文件的 mimeType
// UIImage *image = [UIImage imageNamed:@"test"];
// NSData *filedata = UIImagePNGRepresentation(image);
// [self upload:@"file" filename:@"test.png" mimeType:@"image/png" data:filedata parmas:@{@"username" : @"123"}];
// 给本地文件发送一个请求
NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
NSURLResponse *repsonse = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil];
// 得到mimeType
NSLog(@"%@", repsonse.MIMEType);
[self upload:@"file" filename:@"itcast.txt" mimeType:repsonse.MIMEType data:data parmas:@{@"username":@"tom", @"type":@"xml"}];
附:常见文件类型的MIMEType
Image(47)
ViewController.m
UploadFileDemo
#import "ViewController.h"
#define UTF8Encode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
@interface ViewController ()
- (IBAction)upload;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }
- (IBAction)upload {
UIImage *image = [UIImage imageNamed:@"IMG_0413"];
NSData *imageData = UIImagePNGRepresentation(image);
[self upload:@"uploadedFile" filename:@"IMG_0413.PNG" mimeType:@"image/png" data:imageData parmas:nil];
}
- (void)upload:(NSString *)name filename:(NSString *)filename mimeType:(NSString *)mimeType data:(NSData *)data parmas:(NSDictionary *)params
{
// 文件上传
NSURL *url = [NSURL URLWithString:@"http://192.168.0.21:8080/MyTestServer/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 设置请求体
NSMutableData *body = [NSMutableData data];
/***************文件参数***************/
// 参数开始的标志
[body appendData:UTF8Encode(@"--HelloVoidWorldBoundary\r\n")];
// name : 指定参数名(必须跟服务器端保持一致)
// filename : 文件名
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename];
[body appendData:UTF8Encode(disposition)];
NSString *type = [NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType];
[body appendData:UTF8Encode(type)];
[body appendData:UTF8Encode(@"\r\n")];
[body appendData:data];
[body appendData:UTF8Encode(@"\r\n")];
/***************普通参数***************/
[params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { // 参数开始的标志
[body appendData:UTF8Encode(@"--HelloVoidWorldBoundary\r\n")];
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", key];
[body appendData:UTF8Encode(disposition)];
[body appendData:UTF8Encode(@"\r\n")];
[body appendData:UTF8Encode(obj)];
[body appendData:UTF8Encode(@"\r\n")];
}];
/***************参数结束***************/
// HelloVoidWorldBoundary--\r\n
[body appendData:UTF8Encode(@"--HelloVoidWorldBoundary--\r\n")];
request.HTTPBody = body;
// 设置请求头
// 请求体的长度
[request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
// 声明这个POST请求是个文件上传
[request setValue:@"multipart/form-data; boundary=HelloVoidWorldBoundary" forHTTPHeaderField:@"Content-Type"];
// 发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"开始上传~~~");
if (data) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@", dict); } else {
NSLog(@"上传失败"); }
}];
}
/** 取得本地文件的MIMEType */
- (void) getMIMEType {
//apache-tomcat-6.0.41/conf/web.xml 查找 文件的 mimeType
// UIImage *image = [UIImage imageNamed:@"test"];
// NSData *filedata = UIImagePNGRepresentation(image);
// [self upload:@"file" filename:@"test.png" mimeType:@"image/png" data:filedata parmas:@{@"username" : @"123"}];
// 给本地文件发送一个请求
NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
NSURLResponse *repsonse = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil];
// 得到mimeType
NSLog(@"%@", repsonse.MIMEType);
[self upload:@"file" filename:@"itcast.txt" mimeType:repsonse.MIMEType data:data parmas:@{@"username":@"tom", @"type":@"xml"}]; }