檔案上傳走的是 POST 請求,通常把要上傳的資料放在請求主體中。本文示範不依賴任何第三方框架的做法。由於過程較繁瑣,這裡只列出關鍵程式碼。
#import "YYViewController.h"
#define YYEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
@implementation YYViewController
- (void)upload:(NSString *)name
filename:(NSString *)filename
mimeType:(NSString *)mimeType
data:(NSData *)data
parmas:(NSDictionary *)params {
NSURL *url = [NSURL URLWithString:@"https://192.168.1.200:8080/YYServer/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 組出請求主體
NSMutableData *body = [NSMutableData data];
/*************** 檔案參數 ***************/
// 參數起始標記
[body appendData:YYEncode(@"--YY\r\n")];
// name 必須與伺服器端一致;filename 為檔名
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename];
[body appendData:YYEncode(disposition)];
NSString *type = [NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType];
[body appendData:YYEncode(type)];
[body appendData:YYEncode(@"\r\n")];
[body appendData:data];
[body appendData:YYEncode(@"\r\n")];
/*************** 普通參數 ***************/
[params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[body appendData:YYEncode(@"--YY\r\n")];
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", key];
[body appendData:YYEncode(disposition)];
[body appendData:YYEncode(@"\r\n")];
[body appendData:YYEncode(obj)];
[body appendData:YYEncode(@"\r\n")];
}];
/*************** 參數結束 ***************/
[body appendData:YYEncode(@"--YY--\r\n")];
request.HTTPBody = body;
// 請求標頭
[request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"];
// 送出請求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@", dict);
} else {
NSLog(@"上傳失敗");
}
}];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 上傳本地檔案
NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
NSURLResponse *repsonse = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil];
// 取得 mimeType
NSLog(@"%@", repsonse.MIMEType);
[self upload:@"file" filename:@"itcast.txt" mimeType:repsonse.MIMEType data:data parmas:@{@"username" : @"999", @"type" : @"XML"}];
}
@end
補充:上傳請求的資料格式如下,boundary 兩端的標記必須前後呼應。

常見檔案的 MIMEType 可以參考下表(Tomcat 的 conf/web.xml 裡也能查到):

這裡示範只用蘋果自帶的類,同時開多條執行緒下載同一個大檔案。實作步驟如下:

實現思路:下載開始時,先在沙盒建立一個與伺服器檔案等大的空白檔案(要下載 100M 就先配一個 100M 的檔),接著把總長度切成若干段,開啟多條執行緒各下載一段,再分別寫入檔案對應的偏移位置。
專案中的主要類別:

主控制器:
#import "YYViewController.h"
#import "YYFileMultiDownloader.h"
@interface YYViewController ()
@property (nonatomic, strong) YYFileMultiDownloader *fileMultiDownloader;
@end
@implementation YYViewController
- (YYFileMultiDownloader *)fileMultiDownloader {
if (!_fileMultiDownloader) {
_fileMultiDownloader = [[YYFileMultiDownloader alloc] init];
// 遠端檔案網址
_fileMultiDownloader.url = @"https://192.168.1.200:8080/MJServer/resources/jre.zip";
// 存檔位置
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
_fileMultiDownloader.destPath = [caches stringByAppendingPathComponent:@"jre.zip"];
}
return _fileMultiDownloader;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.fileMultiDownloader start];
}
@end
自訂一個抽象基底類別,統一對外介面:
// YYFileDownloader.h
#import <Foundation/Foundation.h>
@interface YYFileDownloader : NSObject
{
BOOL _downloading;
}
/** 要下載檔案的遠端 URL */
@property (nonatomic, copy) NSString *url;
/** 檔案的儲存路徑 */
@property (nonatomic, copy) NSString *destPath;
/** 是否正在下載(只有下載器內部才知道) */
@property (nonatomic, readonly, getter = isDownloading) BOOL downloading;
/** 監聽下載進度 */
@property (nonatomic, copy) void (^progressHandler)(double progress);
/** 開始(恢復)下載 */
- (void)start;
/** 暫停下載 */
- (void)pause;
@end
單執行緒下載器,負責下載「一段」:
// YYFileSingleDownloader.h #import "YYFileDownloader.h" @interface YYFileSingleDownloader : YYFileDownloader /** 起始位置 */ @property (nonatomic, assign) long long begin; /** 結束位置 */ @property (nonatomic, assign) long long end; @end
// YYFileSingleDownloader.m
#import "YYFileSingleDownloader.h"
@interface YYFileSingleDownloader () <NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSURLConnection *conn;
/** 寫檔用的檔案 handle */
@property (nonatomic, strong) NSFileHandle *writeHandle;
/** 目前已下載的長度 */
@property (nonatomic, assign) long long currentLength;
@end
@implementation YYFileSingleDownloader
- (NSFileHandle *)writeHandle {
if (!_writeHandle) {
_writeHandle = [NSFileHandle fileHandleForWritingAtPath:self.destPath];
}
return _writeHandle;
}
/** 開始(恢復)下載 */
- (void)start {
NSURL *url = [NSURL URLWithString:self.url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 預設 GET
// 關鍵:用 Range 標頭指定要下載的區段
NSString *value = [NSString stringWithFormat:@"bytes=%lld-%lld", self.begin + self.currentLength, self.end];
[request setValue:value forHTTPHeaderField:@"Range"];
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
_downloading = YES;
}
/** 暫停下載 */
- (void)pause {
[self.conn cancel];
self.conn = nil;
_downloading = NO;
}
#pragma mark - NSURLConnectionDataDelegate
/** 1. 收到伺服器回應時呼叫 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}
/** 2. 收到資料時呼叫(可能被呼叫多次,每次只帶部分資料) */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 移動到本段該寫入的位置
[self.writeHandle seekToFileOffset:self.begin + self.currentLength];
[self.writeHandle writeData:data];
self.currentLength += data.length;
double progress = (double)self.currentLength / (self.end - self.begin);
if (self.progressHandler) {
self.progressHandler(progress);
}
}
/** 3. 資料接收完畢 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.currentLength = 0;
[self.writeHandle closeFile];
self.writeHandle = nil;
}
/** 4. 請求失敗(逾時、斷網等) */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
@end
多執行緒下載器:負責把檔案切段、建立與管理多個單執行緒下載器。一個多執行緒下載器只負責一個檔案。
// YYFileMultiDownloader.m
#import "YYFileMultiDownloader.h"
#import "YYFileSingleDownloader.h"
#define YYMaxDownloadCount 4
@interface YYFileMultiDownloader ()
@property (nonatomic, strong) NSMutableArray *singleDownloaders;
@property (nonatomic, assign) long long totalLength;
@end
@implementation YYFileMultiDownloader
/** 取得檔案大小 */
- (void)getFilesize {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
request.HTTPMethod = @"HEAD";
NSURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
self.totalLength = response.expectedContentLength;
}
- (NSMutableArray *)singleDownloaders {
if (!_singleDownloaders) {
_singleDownloaders = [NSMutableArray array];
[self getFilesize];
// 每條執行緒的分攤下載量
long long size = 0;
if (self.totalLength % YYMaxDownloadCount == 0) {
size = self.totalLength / YYMaxDownloadCount;
} else {
size = self.totalLength / YYMaxDownloadCount + 1;
}
// 建立 N 個下載器
for (int i = 0; i < YYMaxDownloadCount; i++) {
YYFileSingleDownloader *singleDownloader = [[YYFileSingleDownloader alloc] init];
singleDownloader.url = self.url;
singleDownloader.destPath = self.destPath;
singleDownloader.begin = i * size;
singleDownloader.end = singleDownloader.begin + size - 1;
singleDownloader.progressHandler = ^(double progress) {
NSLog(@"%d --- %f", i, progress);
};
[_singleDownloaders addObject:singleDownloader];
}
// 建立與伺服器檔案等大的暫存檔
[[NSFileManager defaultManager] createFileAtPath:self.destPath contents:nil attributes:nil];
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:self.destPath];
[handle truncateFileAtOffset:self.totalLength];
}
return _singleDownloaders;
}
/** 開始(恢復)下載 */
- (void)start {
[self.singleDownloaders makeObjectsPerformSelector:@selector(start)];
_downloading = YES;
}
/** 暫停下載 */
- (void)pause {
[self.singleDownloaders makeObjectsPerformSelector:@selector(pause)];
_downloading = NO;
}
@end
最後補充一個實務上的細節:如何取得要下載檔案的大小?用 HEAD 請求讀回應標頭裡的 expectedContentLength 即可。

要留意的是,多段下載能成立的前提是伺服器有回應 Range 標頭(即支援斷點續傳)。若伺服器忽略 Range 直接回 200 與整個檔案,多執行緒寫入就會互相覆蓋,因此正式導入前建議先確認伺服器行為,並在程式碼裡檢查回應狀態碼是否為 206。