原始的方式实现文件上传
文件上传的步骤
- 首先定义一些基本的宏,方便后面使用,因为这些代码实在恶心,不能出现任何差错
#define ZMJBoundary @"zmj"
#define ZMJEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]
#define ZMJNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
- 创建POST请求
NSURL *url = [NSURL URLWithString:@"www.baidu.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
- 设置请求头(告诉告诉服务器,这是一个文件上传的请求)
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", ZMJBoundary] forHTTPHeaderField:@"Content-Type"];
- 设置请求体
- 先创建一个空的请求体
NSMutableData *body = [NSMutableData data];
- 如果是文件参数,必须严格按照以下格式
```
--分割线\r\n
Content-Disposition: form-data; name="参数名"; filename="文件名"\r\n
Content-Type: 文件的MIMEType\r\n
\r\n
文件数据
\r\n
```
```objc
// 实现代码
// 分割线
[body appendData:ZMJEncode(@"--")];
[body appendData:ZMJEncode(ZMJBoundary)];
[body appendData:ZMJNewLine];
// 文件参数名
[body appendData:ZMJEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
[body appendData:ZMJNewLine];
// 文件的类型
[body appendData:ZMJEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
[body appendData:ZMJNewLine];
// 文件数据
[body appendData:ZMJNewLine];
UIImage *image = [UIImage imageNamed:@"placeholder"];
[body appendData:UIImagePNGRepresentation(image)];
// [body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/test.png"]];
[body appendData:ZMJNewLine];
```
- 如果是非文件参数,同样必须遵守以下格式
```
--分割线\r\n
Content-Disposition: form-data; name="参数名"\r\n
\r\n
参数值
\r\n
```
```objc
// 非文件参数代码实现
// 分割线
[body appendData:ZMJEncode(@"--")];
[body appendData:ZMJEncode(ZMJBoundary)];
[body appendData:ZMJNewLine];
// 参数名
[body appendData:ZMJEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\""])];
[body appendData:ZMJNewLine];
// 参数值
[body appendData:ZMJNewLine];
[body appendData:ZMJEncode(@"jack")];
[body appendData:ZMJNewLine];
```
- 最后,添加结束标记,必须遵守格式
```
--分割线--\r\n
```
```objc
// 结束标记代码实现
[body appendData:ZMJEncode(@"--")];
[body appendData:ZMJEncode(ZMJBoundary)];
[body appendData:ZMJEncode(@"--")];
[body appendData:ZMJNewLine];
```
- 设置请求体
```objc
request.HTTPBody = body;
```
- 利用NSURLConnection类发送异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
网友评论