您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 檔案下載與上傳:Range 斷點續傳與 multipart POST 實作

編輯:iOS 開發綜合

檔案傳輸是 App 的基礎設施。這篇把下載與上傳兩條路徑都走一遍:下載端用 HTTP HEAD 取得大小、用 Range 標頭分段抓取並追加寫入以支援斷點續傳;上傳端則手工組出 multipart/form-data 的請求本文。

一、取得遠端檔案大小

做法一:HEAD 請求

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:0
                                                   timeoutInterval:kTimeout];
request.HTTPMethod = @"HEAD";

[NSURLConnection sendAsynchronousRequest:request
                                   queue:self.myQueue
                         completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSLog(@"%@", response);
}];

HEAD 只回傳資源標頭,不含主體。典型用途是取得 MIME 類型、取得檔案大小以支援續傳或多執行緒下載。

做法二:封裝成 block 版本

- (void)fileSizeWithURL:(NSURL *)url completion:(void (^)(long long contentLength))completion {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                          cachePolicy:0
                                                      timeoutInterval:kTimeout];
    request.HTTPMethod = @"HEAD";

    NSURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request
                          returningResponse:&response
                                      error:NULL];
    completion(response.expectedContentLength);
}

二、HTTP Range 的語法

透過 Range 標頭可以指定每次要抓哪一段位元組:

  • bytes=0-499:第 0 到 499,共 500 個位元組。
  • bytes=500-999:第二個 500 位元組。
  • bytes=500-:從 500 直到結尾。
  • bytes=-500:最後 500 個位元組。
  • bytes=500-599,800-899:一次指定多個區段(實務上少用)。

格式規則:前面是起始位元組,後面是結束位元組,省略則代表直到結尾,逗號用於分組。

計算分段範圍

long long fromBytes = 0;
long long toBytes = 0;

while (contentLength > kDownloadBytes) {
    toBytes = fromBytes + kDownloadBytes - 1;
    NSString *range = [NSString stringWithFormat:@"bytes=%lld-%lld", fromBytes, toBytes];
    NSLog(@"range %@", range);

    fromBytes += kDownloadBytes;
    contentLength -= kDownloadBytes;
}

// 最後一段
toBytes = fromBytes + contentLength - 1;
NSLog(@"range bytes=%lld-%lld", fromBytes, toBytes);

注意 - 1:Range 是閉區間,抓 20250 個位元組時結束值是起始值加 20249。

送出分段請求

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                   timeoutInterval:kTimeout];
NSString *range = [NSString stringWithFormat:@"bytes=%lld-%lld", from, end];
[request setValue:range forHTTPHeaderField:@"Range"];

NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
                                    returningResponse:&response
                                                error:NULL];

若請求帶了 Range,伺服器會以 206 Partial Content 回應,而非 200 OK。判斷回應狀態時要記得這一點。

三、把資料追加寫入檔案

// 開啟既有檔案;不存在時回傳 nil
NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:self.cachePath];

if (!fp) {
    // 第一次寫入,直接存檔
    [data writeToFile:self.cachePath atomically:YES];
} else {
    [fp seekToEndOfFile];   // 移到結尾
    [fp writeData:data];    // 追加
    [fp closeFile];         // 關閉
}

四、檢查本地已下載的大小

if ([[NSFileManager defaultManager] fileExistsAtPath:self.cachePath]) {
    NSDictionary *dict = [[NSFileManager defaultManager]
                          attributesOfItemAtPath:self.cachePath error:NULL];
    return [dict[NSFileSize] longLongValue];
}
return 0;

因為資料是「追加」的,所以下載前必須先比對:本地檔案大小若已等於遠端大小,就直接跳過下載,這正是續傳的核心判斷。

五、下載流程組裝

- (void)downloadFileWithURL:(NSURL *)url {
    [self fileSizeWithURL:url completion:^(long long contentLength) {
        NSLog(@"文件總大小:%lld", contentLength);

        while (contentLength > kDownloadBytes) {
            NSLog(@"每次下載長度:%lld", (long long)kDownloadBytes);
            contentLength -= kDownloadBytes;
        }
        NSLog(@"最後下載位元組數:%lld", contentLength);
    }];
}

六、上傳:multipart/form-data

上傳檔案時,請求本文由「分隔線 + 標頭 + 檔案內容」重複組成,最後再補一個結尾分隔線:

static NSString *boundaryStr = @"--";
static NSString *randomIDStr = @"itcast";     // 分隔符識別碼
static NSString *uploadID    = @"uploadFile"; // 伺服器端接收欄位名稱

// 本文開頭:描述即將上傳的檔案
- (NSString *)topStringWithMimeType:(NSString *)mimeType uploadFile:(NSString *)uploadFile {
    NSMutableString *strM = [NSMutableString string];
    [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
    [strM appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\n",
                       uploadID, uploadFile];
    [strM appendFormat:@"Content-Type: %@\n\n", mimeType];
    return [strM copy];
}

// 本文結尾
- (NSString *)bottomString {
    NSMutableString *strM = [NSMutableString string];
    [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
    [strM appendString:@"Content-Disposition: form-data; name=\"submit\"\n\n"];
    [strM appendString:@"Submit\n"];
    [strM appendFormat:@"%@%@--\n", boundaryStr, randomIDStr];
    return [strM copy];
}

// 組裝並送出
- (void)uploadFileWithURL:(NSURL *)url data:(NSData *)data {
    NSString *topStr = [self topStringWithMimeType:@"image/png" uploadFile:@"頭像1.png"];
    NSString *bottomStr = [self bottomString];

    NSMutableData *dataM = [NSMutableData data];
    [dataM appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]];
    [dataM appendData:data];       // 檔案二進位內容
    [dataM appendData:[bottomStr dataUsingEncoding:NSUTF8StringEncoding]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                          cachePolicy:0
                                                      timeoutInterval:2.0f];
    request.HTTPBody = dataM;
    request.HTTPMethod = @"POST";

    // Content-Length 必填,否則伺服器會一直等待
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)dataM.length]
   forHTTPHeaderField:@"Content-Length"];

    // Content-Type 必須帶上 boundary,且要與本文中的分隔線一致
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", randomIDStr];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];

    [NSURLConnection sendAsynchronousRequest:request
                                      queue:[[NSOperationQueue alloc] init]
                            completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", result);
    }];
}

呼叫端:

UploadFile *upload = [[UploadFile alloc] init];
NSString *path = [[NSBundle mainBundle] pathForResource:@"頭像1.png" ofType:nil];
NSData *data = [NSData dataWithContentsOfFile:path];
[upload uploadFileWithURL:[NSURL URLWithString:@"https://localhost/upload.php"] data:data];

七、現代做法建議

上面的程式碼把重點放在「協定本身怎麼運作」,值得讀過一次;但 production 環境請改用以下 API:

  • NSURLSession 取代 NSURLConnection(後者自 iOS 9 起已廢棄),並支援背景下載與自動續傳。
  • NSURLSessionDownloadTask 會由系統管理暫存檔與續傳,你不必自己處理 Range 與檔案追加。
  • NSFileHandle 的同步寫入會阻塞主執行緒,大量資料請改用 writeData: 的搭配 GCD 佇列,或使用 NSData 的 writeToFile:options: 在背景執行。
  • 上傳時若檔案較大,改用 uploadTaskWithRequest:fromFile:,讓系統直接串流讀檔,避免把整個檔案載入記憶體。
  • App Transport Security 要求預設使用 HTTPS,明文 HTTP 需在 Info.plist 中設定例外。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved