原始的方式實(shí)現(xiàn)文件上傳
文件上傳的步驟
- 首先定義一些基本的宏漾月,方便后面使用领迈,因?yàn)檫@些代碼實(shí)在惡心压彭,不能出現(xiàn)任何差錯(cuò)
#define ZMJBoundary @"zmj"
#define ZMJEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]
#define ZMJNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
- 創(chuàng)建POST請(qǐng)求
NSURL *url = [NSURL URLWithString:@"www.baidu.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
- 設(shè)置請(qǐng)求頭(告訴告訴服務(wù)器,這是一個(gè)文件上傳的請(qǐng)求)
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", ZMJBoundary] forHTTPHeaderField:@"Content-Type"];
- 設(shè)置請(qǐng)求體
- 先創(chuàng)建一個(gè)空的請(qǐng)求體
NSMutableData *body = [NSMutableData data];
- 如果是文件參數(shù)运翼,必須嚴(yán)格按照以下格式
```
--分割線\r\n
Content-Disposition: form-data; name="參數(shù)名"; filename="文件名"\r\n
Content-Type: 文件的MIMEType\r\n
\r\n
文件數(shù)據(jù)
\r\n
```
```objc
// 實(shí)現(xiàn)代碼
// 分割線
[body appendData:ZMJEncode(@"--")];
[body appendData:ZMJEncode(ZMJBoundary)];
[body appendData:ZMJNewLine];
// 文件參數(shù)名
[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];
// 文件數(shù)據(jù)
[body appendData:ZMJNewLine];
UIImage *image = [UIImage imageNamed:@"placeholder"];
[body appendData:UIImagePNGRepresentation(image)];
// [body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/test.png"]];
[body appendData:ZMJNewLine];
```
- 如果是非文件參數(shù)双谆,同樣必須遵守以下格式
```
--分割線\r\n
Content-Disposition: form-data; name="參數(shù)名"\r\n
\r\n
參數(shù)值
\r\n
```
```objc
// 非文件參數(shù)代碼實(shí)現(xiàn)
// 分割線
[body appendData:ZMJEncode(@"--")];
[body appendData:ZMJEncode(ZMJBoundary)];
[body appendData:ZMJNewLine];
// 參數(shù)名
[body appendData:ZMJEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\""])];
[body appendData:ZMJNewLine];
// 參數(shù)值
[body appendData:ZMJNewLine];
[body appendData:ZMJEncode(@"jack")];
[body appendData:ZMJNewLine];
```
- 最后壳咕,添加結(jié)束標(biāo)記,必須遵守格式
```
--分割線--\r\n
```
```objc
// 結(jié)束標(biāo)記代碼實(shí)現(xiàn)
[body appendData:ZMJEncode(@"--")];
[body appendData:ZMJEncode(ZMJBoundary)];
[body appendData:ZMJEncode(@"--")];
[body appendData:ZMJNewLine];
```
- 設(shè)置請(qǐng)求體
```objc
request.HTTPBody = body;
```
- 利用NSURLConnection類發(fā)送異步請(qǐng)求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];