動手寫上傳功能之前,得先知道瀏覽器與伺服器之間到底有哪些「溝通方式」。最常見的幾個方法各有分工:
本文要談的 PUT,正是 App 直接上傳檔案到伺服器時相當好用的一種做法。
以 macOS 自帶的 Apache 為例,預設並沒有把 PUT 相關的模組打開,需要手動調整設定。
n 打開終端
p cd /etc/apache2
p sudo vim httpd.conf
n 在 vim 中搜尋
p /httpd-dav.conf
• 找到 httpd-dav.conf 這一行
p 按 0 把游標移到行首
p 按 x 刪除行首的 #
p 輸入 :wq 儲存並離開
cd /etc/apache2/extra
sudo vim httpd-dav.conf
在檔案中把第一處標紅位置的 Digest 改成 Basic,然後 :wq 儲存離開。這一步改的是使用者授權模式。
另外兩處需要注意的設定:
/user/user.passwd)。admin)。cd /usr
sudo htpasswd -c /usr/user.passwd admin
ls -l
sudo chgrp www /usr/user.passwd
ls -l
# 建立 var 資料夾,用來放 DavLockDB 相關檔案
sudo mkdir -p /usr/var
sudo chown -R www:www /usr/var
# 建立上傳資料夾
sudo mkdir -p /usr/uploads
sudo chown -R www:www /usr/uploads
# 重新啟動 Apache
sudo apachectl -k restart
重啟後沒看到錯誤訊息,再用 ls -l 檢查一次。只要能同時看到下面這三項,代表環境已經準備完成:
uploads
user.passwd
var
伺服器準備好之後,接著在 iOS 端實作。重點有三個:組出正確的 URL、把請求方法改成 PUT、再加上 Basic 授權標頭。
#import "KUViewController.h"
#import "KUProgress.h"
@interface KUViewController () <NSURLSessionTaskDelegate>
// 用來顯示進度的自訂 View,繼承自 UIView
@property (weak, nonatomic) IBOutlet KUProgress *progressView;
@end
@implementation KUViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self putFile];
}
/**
* 以 PUT 方法上傳檔案,不經過瀏覽器
*/
-(void)putFile
{
// 1. 組出 URL(協議 + 主機 + 路徑 + 伺服器上的檔名)
// 注意:POST 的 URL 通常指向伺服器上的接收程式,
// 而 PUT 直接把檔案寫到指定路徑
NSString *urlStr = @"https://localhost/uploads/046.Post提交用戶隱私數據&MD5加密.mp4";
// 1.1 先做 URL 編碼,處理中文與特殊字元
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
// 2. 建立 request(預設是 GET)
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 2> 指定請求方法
request.HTTPMethod = @"PUT";
// 3> 加上授權資訊
/**
* Base64 是目前網路上常見的編碼方式,能把二進位資料轉成字串,
* 對方收到後可以再還原成原始檔案。它既能編碼,也能解碼。
*
* 授權三步驟:
* (1) 授權字串格式:使用者名稱:口令
* (2) 授權模式:Basic + Base64 編碼後的授權字串
* (3) 把結果寫進 HTTP Header 的 Authorization 欄位
*/
NSString *authStr = @"admin:admin";
authStr = [self authBase64:authStr]; // 轉成 Base64
NSString *authBase64 = [NSString stringWithFormat:@"Basic %@", authStr];
[request setValue:authBase64 forHTTPHeaderField:@"Authorization"];
// 3. 建立 session
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:[[NSOperationQueue alloc] init]];
// 4. 建立上傳任務
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"01.Post提交用戶隱私數據&MD5加密.mp4"
withExtension:nil];
[[session uploadTaskWithRequest:request fromFile:fileUrl] resume];
// 如果不需要進度條,也可以改用 completionHandler 版本:
// NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request
// fromFile:fileUrl
// completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"str = %@", str);
// }];
}
#pragma mark -- 代理方法
// 上傳進度回呼
-(void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
CGFloat value = (CGFloat)totalBytesSent / totalBytesExpectedToSend;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.progressView.progress = value;
}];
NSLog(@"上傳進度:value = %.03lf", value);
}
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error
{
NSLog(@"上傳失敗");
}
// 把字串轉成 Base64 編碼的授權字串
-(NSString *)authBase64:(NSString *)authStr
{
NSData *data = [authStr dataUsingEncoding:NSUTF8StringEncoding];
return [data base64EncodedStringWithOptions:0];
}
@end
伺服器那邊最常見的失敗原因是目錄權限:Apache 的執行帳號(www)必須對 uploads 有寫入權限,否則 PUT 會被拒絕。客戶端這邊則要留意中文檔名一定要先做 URL 編碼,以及 Authorization 標頭的格式必須是「Basic 空格 Base64字串」,少一個空格就會認證失敗。