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

iOS 上傳工具類 EPUploader:以 multipart/form-data 傳檔

編輯:iOS 開發綜合

這個工具類封裝了「把一筆 NSData 以 HTTP POST 上傳到伺服器」的流程,並透過 doneSelector/errorSelector 回呼結果,讓呼叫端不必接觸 NSURLConnection 的細節。

標頭檔

#import <Foundation/Foundation.h>

@interface EPUploader : NSObject {
    NSURL *serverURL;
    NSData *file;
    id delegate;
    SEL doneSelector;
    SEL errorSelector;
    BOOL uploadDidSucceed;
}

- (id)initWithURL:(NSURL *)serverURL
             file:(NSData *)file
         delegate:(id)delegate
     doneSelector:(SEL)doneSelector
    errorSelector:(SEL)errorSelector;

- (NSData *)file;

@end

實作檔

#import "EPUploader.h"
#import <zlib.h>

static NSString * const BOUNDRY = @"0xKhTmLbOuNdArY";
static NSString * const FORM_FLE_INPUT = @"uploaded";
#define ASSERT(x) NSAssert(x, @"")

@interface EPUploader (Private)
- (void)upload;
- (NSURLRequest *)postRequestWithURL:(NSURL *)url
                             boundry:(NSString *)boundry
                                data:(NSData *)data;
- (void)uploadSucceeded:(BOOL)success;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
@end

初始化時即啟動上傳,並用 ASSERT 把「必要參數不可為 nil」的契約寫清楚:

- (id)initWithURL:(NSURL *)aServerURL
               file:(NSData *)aFile
           delegate:(id)aDelegate
       doneSelector:(SEL)aDoneSelector
      errorSelector:(SEL)anErrorSelector {
    if ((self = [super init])) {
        ASSERT(aServerURL);
        ASSERT(aFile);
        ASSERT(aDelegate);
        ASSERT(aDoneSelector);
        ASSERT(anErrorSelector);

        serverURL     = aServerURL;
        file          = aFile;
        delegate      = aDelegate;
        doneSelector  = aDoneSelector;
        errorSelector = anErrorSelector;

        [self upload];
    }
    return self;
}

- (void)dealloc {
    serverURL = nil;
    file = nil;
    delegate = nil;
    doneSelector = NULL;
    errorSelector = NULL;
}

- (NSData *)file {
    return file;
}

上傳主流程,包含空資料的處理:

- (void)upload {
    ASSERT(file);
    if (!file) {
        [self uploadSucceeded:NO];
        return;
    }

    if ([file length] == 0) {
        // 沒有資料,視同沒有檔案,當作成功處理
        [self uploadSucceeded:YES];
        return;
    }

    NSURLRequest *urlRequest = [self postRequestWithURL:serverURL boundry:BOUNDRY data:file];
    if (!urlRequest) {
        [self uploadSucceeded:NO];
        return;
    }

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    if (!connection) {
        [self uploadSucceeded:NO];
    }
    // 之後等待連線回呼
}

粗 Assemble multipart 本文的關鍵,是嚴格遵守 boundary 的格式:每一段以「--boundary」開頭,接著是 Content-Disposition 標頭與一個空行,然後才是二進位內容,最後以「--boundary--」收尾。

- (NSURLRequest *)postRequestWithURL:(NSURL *)url
                              boundry:(NSString *)boundry
                                 data:(NSData *)data {
    // 參考:https://www.cocoadev.com/index.pl?HTTPFileUpload
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry]
      forHTTPHeaderField:@"Content-Type"];

    NSNumber *ranNum = [NSNumber numberWithInt:arc4random() % 1000000];
    NSMutableData *postData = [NSMutableData dataWithCapacity:[data length] + 512];

    [postData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundry]
                          dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[[NSString stringWithFormat:
        @"Content-Disposition: form-data; name=\"%@\"; filename=\"image%@.png\"\r\n\r\n",
        FORM_FLE_INPUT, ranNum] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:data];
    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundry]
                          dataUsingEncoding:NSUTF8StringEncoding]];

    [urlRequest setHTTPBody:postData];
    return urlRequest;
}

結果回呼與連線委派:

- (void)uploadSucceeded:(BOOL)success {
    [delegate performSelector:success ? doneSelector : errorSelector withObject:self];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"%s: self:0x%p\n", __func__, self);
    [self uploadSucceeded:uploadDidSucceed];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"%s: self:0x%p, connection error:%s\n",
          __func__, self, [[error description] UTF8String]);
    [self uploadSucceeded:NO];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"%s: self:0x%p\n", __func__, self);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"%s: self:0x%p\n", __func__, self);
    NSString *reply = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%s: data: %s\n", __func__, [reply UTF8String]);
    if ([reply hasPrefix:@"YES"]) {
        uploadDidSucceed = YES;
    }
}

值得注意的地方:伺服器的回應被約定為以 YES 或 NO 開頭,成敗判定完全依賴這個默契;boundary 字串必須與 Content-Type 標頭完全一致,否則伺服器會解析失敗;另外,原檔中保留了一段以 zlib 壓縮的程式碼(已註解),可見在早期網路環境下,先壓縮再上傳是常見做法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved