NSURLConnection 的 delegate 模式雖然程式碼量偏多,卻提供了許多高階 API 難以取代的能力:串流處理、進度回報、URL 認證與中途取消。本文以 Node.js 為伺服器端,走一遍完整的檔案傳輸流程。
// 回傳檔案流
function download(req, res) {
var downloadFilePath = "./1.jpg";
var filename = path.basename(downloadFilePath);
var filesize = fs.readFileSync(downloadFilePath).length;
res.setHeader('Content-Disposition', 'attachment;filename=' + filename); // 關鍵標頭
res.setHeader('Content-Length', filesize);
res.setHeader('Content-Type', 'application/octet-stream');
var fileStream = fs.createReadStream(downloadFilePath, { bufferSize: 1024 * 1024 });
fileStream.pipe(res, { end: true });
}
// 路由分派
handler: function (req, res) {
switch (req.url) {
case '/': get(req, res); break;
case '/download': download(req, res); break;
}
}
Content-Length 是進度計算的基礎,客戶端必須靠它才知道總量;Content-Disposition 則讓瀏覽器知道這是附件下載。
- (void)download {
NSString *urlString = @"https://localhost:8001/download";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet URLQueryAllowedCharacterSet]]];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
// 收到回應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"=================didReceiveResponse=================");
NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
NSLog(@"response:%@", resp);
}
// 收到資料(大檔案會被呼叫多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"=================didReceiveData=================");
NSLog(@"data.length:%lu", (unsigned long)data.length);
}
當伺服器回傳的是小圖片(約 19KB)時,didReceiveData 只被呼叫一次就完成傳輸。把伺服器端的檔案換成一張較大的圖片(約 1.2MB)再測一次,didReceiveData 便被反覆呼叫十餘次,每次 65536 位元組左右,最後一片略大於前面幾片。
由此可以推出進度算法:把每次回調的 data.length 累加,除以回應標頭中的 Content-Length 即可。
// 取得檔案總大小 // [[((NSHTTPURLResponse *)response) allHeaderFields] objectForKey:@"Content-Length"]
資料收齊後,可直接把二進位轉為 UIImage 顯示:
UIImage *img = [UIImage imageWithData:data]; UIImageView *imageView = [[UIImageView alloc] initWithImage:img]; [imageView setFrame:CGRectMake(30, 30, 200, 200)]; [self.view addSubview:imageView];
// 檔案上傳
function upload(req, res) {
var form = new formidable.IncomingForm();
form.encoding = 'utf-8';
form.uploadDir = './upload/';
form.keepExtensions = true;
form.maxFieldsSize = 10 * 1024 * 1024;
form.parse(req, function (err, fields, files) {
if (err) { res.send(err); return; }
var extName = /\.[^\.]+/.exec(files.file.name);
var ext = Array.isArray(extName) ? extName[0] : '';
var avatarName = uuid() + ext; // 重新命名,避免檔名重複
var newPath = form.uploadDir + avatarName;
fs.renameSync(files.file.path, newPath);
var msg = { "status": 1, "msg": "succeed" };
res.write(JSON.stringify(msg));
res.end();
});
}
前面的範例都沒有特別設定請求標頭,因為預設值 application/x-www-form-urlencoded 已足夠傳遞文字參數:GET 時放在 URL,POST 時放在請求體。但這個標頭無法承載檔案,上傳時必須改為:
Content-Type: multipart/form-data; boundary=YY
boundary 用於標示各段內容的分界,可自訂名稱,實際使用時前面要加上兩個減號,例如 --YY,全部傳完後則以 --YY-- 收尾。
/** 設定請求標頭 */ // 請求體長度 [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"]; // 宣告為檔案上傳 [request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"]; [request setHTTPMethod:@"POST"];
- (void)upload {
#define Encode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
NSURL *dataurl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"IMG_0222" ofType:@"jpg"]];
NSData *data = [NSData dataWithContentsOfURL:dataurl];
NSString *urlString = @"https://localhost:8001/upload";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet URLQueryAllowedCharacterSet]]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10];
NSMutableData *body = [NSMutableData data];
// 第一段的起始標記
[body appendData:Encode(@"--YY\r\n")];
// name 必須與伺服器端一致;filename 為原始檔名
NSString *disposition = [NSString stringWithFormat:
@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", @"file", @"1.jpg"];
[body appendData:Encode(disposition)];
NSString *type = [NSString stringWithFormat:@"Content-Type: %@\r\n", @"multipart/form-data"];
[body appendData:Encode(type)];
[body appendData:Encode(@"\r\n")];
// 檔案內容
[body appendData:data];
[body appendData:Encode(@"\r\n")];
// 結束標記
[body appendData:Encode(@"--YY--\r\n")];
[request setHTTPBody:body];
[request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
// 上傳進度
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
NSLog(@"didSendBodyData:%ld, totalBytesWritten:%ld, total:%ld",
(long)bytesWritten, (long)totalBytesWritten, (long)totalBytesExpectedToWrite);
NSLog(@"上傳進度%ld%%", (long)(totalBytesWritten * 100 / totalBytesExpectedToWrite));
}
實測上傳一張約 1.2MB 的圖片,這個方法會被呼叫近四十次,每次帶回本次寫入量、累計寫入量與總量,進度從 2% 一路遞增到 100%。伺服器端印出的請求標頭則可確認 multipart/form-data 與 boundary 是否正確:
{
host: 'localhost:8001',
'content-type': 'multipart/form-data; boundary=YY',
connection: 'keep-alive',
accept: '*/*',
'content-length': '1265418',
'accept-language': 'en-us',
'accept-encoding': 'gzip, deflate'
}
程式碼量確實偏多,但換來的是幾項無可取代的能力:
・以串流方式處理檔案,不必把整個檔案載入記憶體
・上傳與下載都能取得即時進度
・可處理 URL 認證流程
・可在傳輸途中取消請求
取消的做法很直接,在進度回調中判斷門檻後呼叫 cancel 即可:
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
// 上傳超過 50% 時取消
if ((totalBytesWritten * 100 / totalBytesExpectedToWrite) > 50) {
[connection cancel];
}
}
測試時請務必使用較大的檔案,因為檔案太小的話可能根本不會進入這個回調,也就看不到取消效果。
NSURLConnection 在 iOS 9 之後已被標記為過時,新專案應改用 NSURLSession。好處是 API 更簡潔,並可透過 NSURLSessionDownloadTask 直接串流寫檔、暫停與續傳,進度則由 downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: 回報,概念與本文示範的 delegate 完全一致。理解底層的 multipart 協議與分片機制, Moving 到 NSURLSession 時會順暢許多。