1 //文件上传底层原理分析
2 #pragma mark 文件上传
3 - (void)upload {
4 NSURL *url = [NSURL URLWithString:@"http://192.168.1.106:8080/MJServer/upload"];
5
6 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
7 request.HTTPMethod = @"POST";
8
9 // 设置请求头信息-数据类型
10 [request setValue:@"multipart/form-data; boundary=mj" forHTTPHeaderField:@"Content-Type"];
11
12 // 拼接请求体
13 NSMutableData *data = [NSMutableData data];
14
15 // 普通参数-username
16 // 普通参数开始的一个标记
17 [data appendData:Data(@"--mj\r\n")];
18 // 参数描述
19 [data appendData:Data(@"Content-Disposition:form-data; name=\"username\"\r\n")];
20 // 参数值
21 [data appendData:Data(@"\r\n123456\r\n")];
22
23
24 // 文件参数-file
25 // 文件参数开始的一个标记
26 [data appendData:Data(@"--mj\r\n")];
27 // 文件参数描述
28 [data appendData:Data(@"Content-Disposition:form-data; name=\"file\"; filename=\"img.png\"\r\n")];
29 // 文件的MINETYPE
30 [data appendData:Data(@"Content-Type:image/png\r\n")];
31 // 文件内容
32 [data appendData:Data(@"\r\n")];
33 UIImage *image = [UIImage imageNamed:@"Default.png"];
34 NSData *filedata = UIImagePNGRepresentation(image);
35 [data appendData:filedata];
36 [data appendData:Data(@"\r\n")];
37
38 // 参数结束的标识
39 [data appendData:Data(@"--mj--")];
40
41 // 设置请求体
42 request.HTTPBody = data;
43
44 [[NSURLConnection connectionWithRequest:request delegate:nil] start];
45 }
1 #pragma mark 同步请求-获取文件的MIMEType
2 - (void)getType {
3 NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/yyh.txt"];
4 NSURLRequest *request = [NSURLRequest requestWithURL:url];
5
6 // 发送一个同步请求
7 NSURLResponse *response = nil;
8
9 // 发送一个同步请求--阻塞式
10 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
11
12 NSString *type = [response MIMEType];
13 NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
14
15 NSLog(@"%@", str);
16 NSLog(@"%@", type);
17 }
1 #pragma mark 异步请求
2 - (void)post2 {
3 NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/yyh.txt"];
4 NSURLRequest *request = [NSURLRequest requestWithURL:url];
5
6
7 // 这个操作队列是用来执行Block的
8 NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
9 [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
10 // 请求结束后会回调这个Block
11 ^(NSURLResponse *response, NSData *data, NSError *error) {
12 NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
13
14 NSLog(@"%@", str);
15
16 NSLog(@"%@", [response MIMEType]);
17 }];
18 }
1 #pragma mark 每发送一段数据给服务器,就会调用这个方法。这个方法可以用来监听文件上传进度
2 - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
3
4 }