WiFi文件上传框架SGWiFiUpload

背景

在iOS端由于文件系统的封闭性,文件的上传变得十分麻烦,一个比较好的解决方案是通过局域网WiFi来传输文件并存储到沙盒中。

简介

SGWiFiUpload是一个基于CocoaHTTPServer的WiFi上传框架。CocoaHTTPServer是一个可运行于iOS和OS X上的轻量级服务端框架,可以处理GET和POST请求,通过对代码的初步改造,实现了iOS端的WiFi文件上传与上传状态监听。

下载与使用

目前已经做成了易用的框架,上传到了GitHub,点击这里进入,欢迎Star!

请求的处理

CocoaHTTPServer通过HTTPConnection这一接口实现类来回调网络请求的各个状态,包括对请求头、响应体的解析等。为了实现文件上传,需要自定义一个继承HTTPConnection的类,这里命名为SGHTTPConnection,与文件上传有关的几个方法如下。

解析文件上传的请求头

- (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;
    }
    // 这里用于发出文件开始上传的通知
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:SGFileUploadDidStartNotification object:@{@"fileName" : filename ?: @"File"}];
    });
    // 这里用于设置文件的保存路径,先预存一个空文件,然后进行追加写内容
    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]];
    }
}

其中有中文注释的两处是比较重要的地方,这里根据请求头发出了文件开始上传的通知,并且往要存放的路径写一个空文件,以便后续追加内容。

上传过程中的处理

- (void) processContent:(NSData*) data WithHeader:(MultipartMessageHeader*) header 
{
    // here we just write the output from parser to the file.
    // 由于除去文件内容外,还有HTML内容和空文件通过此方法处理,因此需要过滤掉HTML和空文件内容
    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];
    }
}

这里除了拼接文件内容以外,还发出了上传进度的通知,当前方法中只能拿到这一段文件的长度,总长度需要通过下面的方法拿到。

获取文件大小

- (void)prepareForBodyWithSize:(UInt64)contentLength
{
    HTTPLogTrace();
    // 设置文件总大小,并初始化当前已经传输的文件大小。
    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.
    // 由于除去文件内容外,还有HTML内容和空文件通过此方法处理,因此需要过滤掉HTML和空文件内容
    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];
    });
}

这里关闭了文件管道,并且发出了文件上传完毕的通知。

开启Server

CocoaHTTPServer默认的Web根目录为MainBundle,他会在目录下寻找index.html,文件上传的请求地址为upload.html,当以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中发送POST请求上传文件

在CocoaHTTPServer给出的样例中有用于文件上传的index.html,要实现文件上传,只需要一个POST方法的form表单,action为upload.html,每一个文件使用一个input标签,type为file即可,这里为了美观对input标签进行了自定义。
下面的代码演示了能同时上传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页面,该页面用于说明上传完毕,下面的代码实现了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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,099评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,654评论 18 139
  • 本文包括:1、文件上传概述2、利用 Commons-fileupload 组件实现文件上传3、核心API——Dis...
    廖少少阅读 12,549评论 5 91
  • 吃素一直都是很多人倡导的生活方式,并也践行此道。从身体状况讲吃素短期是能够清理肠胃,长期可以减轻身体中的外来激素、...
    经融南安阅读 375评论 0 0
  • 1 三个月前在某个论坛上碰到了CC,我俩大概有3年多没见了。她是北京姑娘,性子直爽,做事果断,特别符合北方姑娘在我...
    半斤鳕鱼阅读 2,023评论 0 0