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

iOS 與 Node 之間上傳與下載檔案

編輯:iOS 開發綜合

上傳與下載需要 server 與 client 相互配合。相同的客戶端程式碼,在 servlet 能成功,換成 node 卻可能失敗,反之亦然,因為不同服務端對 HTTP 請求的處理方式不同。本文介紹服務端使用 node、客戶端使用 NSURLSession 的情況。

服務端程式碼

還沒見過比 node + express 更簡單的實作方式:

var express = require("express");
var app = express();
app.use(express.bodyParser({ uploadDir: __dirname + '/../var/uploads', keepExtensions: true, limit: 100 * 1024 * 1024, defer: true }))
  .use('/svc/public', express.static(__dirname + '/../public'));
app.post('/svc/upload', function (req, res) {
    req.form.on('progress', function (bytesReceived, bytesExpected) {});
    req.form.on('end', function () {
        var tmp_path = req.files.file.path;
        var name = req.files.file.name;
        res.end("success");
    });
});
app.listen(3000);

defer 屬性設為 true,下面的生命週期回呼才會生效。不過這個服務若直接用 CocoaRestClient 發 POST 請求會呼叫不通,似乎需要在 HTTP header 加上 Content-Type。

上傳的客戶端程式碼

主要實作 NSURLSessionTaskDelegate 協議,因為需要其中的生命週期方法來實現進度條:

@interface YLSUploadViewController : UIViewController <NSURLSessionTaskDelegate>
-(void) doUpload;
@end

初始化 boundary、fileParam 與 uploadURL:

boundary = @"----------V2ymHFg03ehbqgZCaKO6jy";
fileParam = @"file";
uploadURL = [NSURL URLWithString:@"https://192.168.1.103:3000/svc/upload"];

最關鍵的方法:NSURLSessionUploadTask 不會自動加上 Content-Type 頭,因此必須手動設定:

-(void) doUpload {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
        NSData *body = [self prepareDataForUpload];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
        [request setHTTPMethod:@"POST"];
        // 關鍵:手動加上 Content-Type
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
        [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
        NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
            NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [session invalidateAndCancel];
        }];
        [uploadTask resume];
    });
}

由於 NSURLSession 不會自動加上 Content-Type 與 boundary,因此要自行從檔案讀出 Data 並拼接所需的分隔符(在 prepareDataForUpload 中完成):

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParam, fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:dataOfFile];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

實作中只需一個 delegate 方法即可更新進度:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend

實務上,應把業務邏輯類別設為上傳元件的 delegate,因為上傳後該做什麼應由業務元件控制。

下載的客戶端程式碼

下載比上傳簡單許多:

-(void) doDownload {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
        NSURL *url = [NSURL URLWithString:@"https://192.168.1.103:3000/svc/public/bigfile.dmg"];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
        [request setHTTPMethod:@"GET"];
        // 使用 downloadTaskWithRequest: 而非帶 block 的版本,否則 delegate 不會被呼叫
        NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];
        [downloadTask resume];
    });
}

下載進度可透過以下 delegate 方法實現:

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite

下載後的檔案放在 tmp 目錄,若不處理很快會被移除,因此需在另一個 delegate 方法中複製到最終路徑:

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *distFilePath = [documentsDirectory stringByAppendingPathComponent:@"success.dmg"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:[location path]]) {
        [fileManager copyItemAtPath:[location path] toPath:distFilePath error:nil];
    }
    [session invalidateAndCancel];
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved