WiFi文件上傳框架SGWiFiUpload

背景

在iOS端由于文件系統(tǒng)的封閉性鸽捻,文件的上傳變得十分麻煩片仿,一個比較好的解決方案是通過局域網(wǎng)WiFi來傳輸文件并存儲到沙盒中。

簡介

SGWiFiUpload是一個基于CocoaHTTPServer的WiFi上傳框架。CocoaHTTPServer是一個可運行于iOS和OS X上的輕量級服務(wù)端框架,可以處理GET和POST請求闽颇,通過對代碼的初步改造,實現(xiàn)了iOS端的WiFi文件上傳與上傳狀態(tài)監(jiān)聽寄锐。

下載與使用

目前已經(jīng)做成了易用的框架兵多,上傳到了GitHub尖啡,點擊這里進入,歡迎Star剩膘!

請求的處理

CocoaHTTPServer通過HTTPConnection這一接口實現(xiàn)類來回調(diào)網(wǎng)絡(luò)請求的各個狀態(tài)衅斩,包括對請求頭、響應(yīng)體的解析等援雇。為了實現(xiàn)文件上傳矛渴,需要自定義一個繼承HTTPConnection的類,這里命名為SGHTTPConnection惫搏,與文件上傳有關(guān)的幾個方法如下。

解析文件上傳的請求頭

- (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header {
    
    // in this sample, we are not interested in parts, other then file parts.
    // check content disposition to find out filename

    MultipartMessageHeaderField* disposition = [header.fields objectForKey:@"Content-Disposition"];
    NSString* filename = [[disposition.params objectForKey:@"filename"] lastPathComponent];

    if ( (nil == filename) || [filename isEqualToString: @""] ) {
        // it's either not a file part, or
        // an empty form sent. we won't handle it.
        return;
    }
    // 這里用于發(fā)出文件開始上傳的通知
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:SGFileUploadDidStartNotification object:@{@"fileName" : filename ?: @"File"}];
    });
    // 這里用于設(shè)置文件的保存路徑蚕涤,先預(yù)存一個空文件筐赔,然后進行追加寫內(nèi)容
    NSString *uploadDirPath = [SGWiFiUploadManager sharedManager].savePath;
    BOOL isDir = YES;
    if (![[NSFileManager defaultManager]fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
        [[NSFileManager defaultManager]createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString* filePath = [uploadDirPath stringByAppendingPathComponent: filename];
    if( [[NSFileManager defaultManager] fileExistsAtPath:filePath] ) {
        storeFile = nil;
    }
    else {
        HTTPLogVerbose(@"Saving file to %@", filePath);
        if(![[NSFileManager defaultManager] createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil]) {
            HTTPLogError(@"Could not create directory at path: %@", filePath);
        }
        if(![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {
            HTTPLogError(@"Could not create file at path: %@", filePath);
        }
        storeFile = [NSFileHandle fileHandleForWritingAtPath:filePath];
        [uploadedFiles addObject: [NSString stringWithFormat:@"/upload/%@", filename]];
    }
}

其中有中文注釋的兩處是比較重要的地方,這里根據(jù)請求頭發(fā)出了文件開始上傳的通知揖铜,并且往要存放的路徑寫一個空文件茴丰,以便后續(xù)追加內(nèi)容。

上傳過程中的處理

- (void) processContent:(NSData*) data WithHeader:(MultipartMessageHeader*) header 
{
    // here we just write the output from parser to the file.
    // 由于除去文件內(nèi)容外天吓,還有HTML內(nèi)容和空文件通過此方法處理贿肩,因此需要過濾掉HTML和空文件內(nèi)容
    if (!header.fields[@"Content-Disposition"]) {
        return;
    } else {
        MultipartMessageHeaderField *field = header.fields[@"Content-Disposition"];
        NSString *fileName = field.params[@"filename"];
        if (fileName.length == 0) return;
    }
    self.currentLength += data.length;
    CGFloat progress;
    if (self.contentLength == 0) {
        progress = 1.0f;
    } else {
        progress = (CGFloat)self.currentLength / self.contentLength;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
       [[NSNotificationCenter defaultCenter] postNotificationName:SGFileUploadProgressNotification object:@{@"progress" : @(progress)}]; 
    });
    if (storeFile) {
        [storeFile writeData:data];
    }
}

這里除了拼接文件內(nèi)容以外,還發(fā)出了上傳進度的通知龄寞,當(dāng)前方法中只能拿到這一段文件的長度汰规,總長度需要通過下面的方法拿到。

獲取文件大小

- (void)prepareForBodyWithSize:(UInt64)contentLength
{
    HTTPLogTrace();
    // 設(shè)置文件總大小物邑,并初始化當(dāng)前已經(jīng)傳輸?shù)奈募笮 ?    self.contentLength = contentLength;
    self.currentLength = 0;
    // set up mime parser
    NSString* boundary = [request headerField:@"boundary"];
    parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
    parser.delegate = self;

    uploadedFiles = [[NSMutableArray alloc] init];
}

處理傳輸完畢

- (void) processEndOfPartWithHeader:(MultipartMessageHeader*) header
{
    // as the file part is over, we close the file.
    // 由于除去文件內(nèi)容外溜哮,還有HTML內(nèi)容和空文件通過此方法處理,因此需要過濾掉HTML和空文件內(nèi)容
    if (!header.fields[@"Content-Disposition"]) {
        return;
    } else {
        MultipartMessageHeaderField *field = header.fields[@"Content-Disposition"];
        NSString *fileName = field.params[@"filename"];
        if (fileName.length == 0) return;
    }
    [storeFile closeFile];
    storeFile = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:SGFileUploadDidEndNotification object:nil];
    });
}

這里關(guān)閉了文件管道色解,并且發(fā)出了文件上傳完畢的通知茂嗓。

開啟Server

CocoaHTTPServer默認的Web根目錄為MainBundle,他會在目錄下尋找index.html科阎,文件上傳的請求地址為upload.html述吸,當(dāng)以POST方式請求upload.html時,請求會被Server攔截锣笨,并且交由HTTPConnection處理蝌矛。

- (BOOL)startHTTPServerAtPort:(UInt16)port {
    HTTPServer *server = [HTTPServer new];
    server.port = port;
    self.httpServer = server;
    [self.httpServer setDocumentRoot:self.webPath];
    [self.httpServer setConnectionClass:[SGHTTPConnection class]];
    NSError *error = nil;
    [self.httpServer start:&error];
    return error == nil;
}

在HTML中發(fā)送POST請求上傳文件

在CocoaHTTPServer給出的樣例中有用于文件上傳的index.html,要實現(xiàn)文件上傳票唆,只需要一個POST方法的form表單朴读,action為upload.html,每一個文件使用一個input標(biāo)簽走趋,type為file即可衅金,這里為了美觀對input標(biāo)簽進行了自定義。
下面的代碼演示了能同時上傳3個文件的index.html代碼。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">
    </head>
    <style>
    body {
        margin: 0px;
        padding: 0px;
        font-size: 12px;
        background-color: rgb(244,244,244);
        text-align: center;
    }
    #container {
        margin: auto;
    }
    
    #form {
        margin-top: 60px;
    }
    
    .upload {
        margin-top: 2px;
    }
    
    #submit input {
        background-color: #ea4c88;
        color: #eee;
        font-weight: bold;
        margin-top: 10px;
        text-align: center;
        font-size: 16px;
        border: none;
        width: 120px;
        height: 36px;
    }
    
    #submit input:hover {
        background-color: #d44179;
    }
    
    #submit input:active {
        background-color: #a23351;
    }
    
    .uploadField {
        margin-top: 2px;
        width: 200px;
        height: 22px;
        font-size: 12px;
    }
    
    .uploadButton {
        background-color: #ea4c88;
        color: #eee;
        font-weight: bold;
        text-align: center;
        font-size: 15px;
        border: none;
        width: 80px;
        height: 26px;
    }
    
    .uploadButton:hover {
        background-color: #d44179;
    }
    
    .uploadButton:active {
        background-color: #a23351;
    }
    
    </style>
    <body>
        <div id="container">
            <div id="form">
                <h2>WiFi File Upload</h2>
                <form name="form" action="upload.html" method="post" enctype="multipart/form-data" accept-charset="utf-8">
                    <div class="upload">
                        <input type="file" name="upload1" id="upload1" style="display:none" onChange="document.form.path1.value=this.value">
                            <input class="uploadField" name="path1" readonly>
                                <input class="uploadButton" type="button" value="Open" onclick="document.form.upload1.click()">
                    </div>
                    <div class="upload">
                        <input type="file" name="upload2" id="upload2" style="display:none" onChange="document.form.path2.value=this.value">
                            <input class="uploadField" name="path2" readonly>
                                <input class="uploadButton" type="button" value="Open" onclick="document.form.upload2.click()">
                    </div>
                    <div class="upload">
                        <input type="file" name="upload3" id="upload3" style="display:none" onChange="document.form.path3.value=this.value">
                            <input class="uploadField" name="path3" readonly>
                                <input class="uploadButton" type="button" value="Open" onclick="document.form.upload3.click()">
                                    </div>
                    <div id="submit"><input type="submit" value="Submit"></div>
                </form>
            </div>
        </div>
    </body>
</html>

表單提交后氮唯,會進入upload.html頁面鉴吹,該頁面用于說明上傳完畢,下面的代碼實現(xiàn)了3秒后的重定向返回惩琉。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">
        <meta http-equiv=refresh content="3;url=index.html">
    </head>
    <body>
        <h3>Upload Succeeded!</h3>
        <p>The Page will be back in 3 seconds</p>
    </body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末豆励,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子瞒渠,更是在濱河造成了極大的恐慌良蒸,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件伍玖,死亡現(xiàn)場離奇詭異嫩痰,居然都是意外死亡,警方通過查閱死者的電腦和手機窍箍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門串纺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人椰棘,你說我怎么就攤上這事纺棺。” “怎么了邪狞?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵祷蝌,是天一觀的道長。 經(jīng)常有香客問我外恕,道長杆逗,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任鳞疲,我火速辦了婚禮罪郊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘尚洽。我一直安慰自己悔橄,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布腺毫。 她就那樣靜靜地躺著癣疟,像睡著了一般。 火紅的嫁衣襯著肌膚如雪潮酒。 梳的紋絲不亂的頭發(fā)上睛挚,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機與錄音急黎,去河邊找鬼扎狱。 笑死侧到,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的淤击。 我是一名探鬼主播匠抗,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼污抬!你這毒婦竟也來了汞贸?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤印机,失蹤者是張志新(化名)和其女友劉穎矢腻,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體射赛,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡踏堡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了咒劲。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡诫隅,死狀恐怖腐魂,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情逐纬,我是刑警寧澤蛔屹,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站豁生,受9級特大地震影響兔毒,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜甸箱,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一育叁、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧芍殖,春花似錦豪嗽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至窃躲,卻和暖如春计贰,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蒂窒。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工躁倒, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留荞怒,地道東北人。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓樱溉,卻偏偏與公主長得像挣输,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子福贞,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,110評論 25 707
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理撩嚼,服務(wù)發(fā)現(xiàn),斷路器挖帘,智...
    卡卡羅2017閱讀 134,654評論 18 139
  • 本文包括:1完丽、文件上傳概述2、利用 Commons-fileupload 組件實現(xiàn)文件上傳3拇舀、核心API——Dis...
    廖少少閱讀 12,549評論 5 91
  • 吃素一直都是很多人倡導(dǎo)的生活方式逻族,并也踐行此道。從身體狀況講吃素短期是能夠清理腸胃骄崩,長期可以減輕身體中的外來激素聘鳞、...
    經(jīng)融南安閱讀 375評論 0 0
  • 1 三個月前在某個論壇上碰到了CC抠璃,我倆大概有3年多沒見了。她是北京姑娘脱惰,性子直爽搏嗡,做事果斷,特別符合北方姑娘在我...
    半斤鱈魚閱讀 2,023評論 0 0