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>
WiFi文件上传框架SGWiFiUpload的更多相关文章
- upload4j安全、高效、易用的java http文件上传框架
简介 upload4j是一款轻量级http文件上传框架,使用简单,实现高效,功能专一,摆脱传统http文件上传框架的繁琐. upload4j的诞生并不是为了解决所有上传需求,而是专注于基础通用需求. ...
- Struts2文件上传和下载(原理)
转自:http://zhou568xiao.iteye.com/blog/220732 1. 文件上传的原理:表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:1) ...
- Struts2 文件上传,下载,删除
本文介绍了: 1.基于表单的文件上传 2.Struts 2 的文件下载 3.Struts2.文件上传 4.使用FileInputStream FileOutputStream文件流来上传 5.使用Fi ...
- 2013第38周日Java文件上传下载收集思考
2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...
- 笔记:Struts2 文件上传和下载
为了上传文件必须将表单的method设置为POST,将 enctype 设置为 muiltipart/form-data,只有设置为这种情况下,浏览器才会把用户选择文件的二进制数据发送给服务器. 上传 ...
- Struts2单文件上传原理及示例
一.文件上传的原理 表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值: 1.application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里 ...
- [转]Struts2多个文件上传
转载至:http://blog.csdn.net/hanxiaoshuang123/article/details/7342091 Struts2多个文件上传多个文件上传分为List集合和数组,下面我 ...
- 使用apache-fileupload处理文件上传与上传多个文件 二(60)
一 使用apache-fileupload处理文件上传 框架:是指将用户经常处理的业务进行一个代码封装.让用户可以方便的调用. 目前文件上传的(框架)组件: Apache----fileupload ...
- Struts2笔记--文件上传
Servlet 3.0规范的HttpServletRequest已经提供了方法来处理文件上传但这种上传需要在Servlet中完成.而Struts2则提供了更简单的封装. Struts2默认使用的是Ja ...
随机推荐
- scrapy分布式的几个重点问题
我们之前的爬虫都是在同一台机器运行的,叫做单机爬虫.scrapy的经典架构图也是描述的单机架构.那么分布式爬虫架构实际上就是:由一台主机维护所有的爬取队列,每台从机的sheduler共享该队列,协同存 ...
- MyBatis 与 Spring 整合
MyBatis-Spring 项目 目前大部分的 Java 互联网项目,都是用 Spring MVC + Spring + MyBatis 搭建平台的. 使用 Spring IoC 可以有效的管理各类 ...
- [LeetCode] Smallest Range 最小的范围
You have k lists of sorted integers in ascending order. Find the smallest range that includes at lea ...
- MySQL · 引擎特性 · InnoDB 同步机制
前言 现代操作系统以及硬件基本都支持并发程序,而在并发程序设计中,各个进程或者线程需要对公共变量的访问加以制约,此外,不同的进程或者线程需要协同工作以完成特征的任务,这就需要一套完善的同步机制,在Li ...
- 使用数据库乐观锁解决高并发秒杀问题,以及如何模拟高并发的场景,CyclicBarrier和CountDownLatch类的用法
数据库:mysql 数据库的乐观锁:一般通过数据表加version来实现,相对于悲观锁的话,更能省数据库性能,废话不多说,直接看代码 第一步: 建立数据库表: CREATE TABLE `skill_ ...
- .NET CORE 2.0之 依赖注入在类中获取IHostingEnvironment,HttpContext
在.NET CORE 中,依赖注入非常常见, 在原先的 HttpContext中常用的server.Mappath已经么有了如下: HttpContext.Current.Server.MapPath ...
- day 1——字典树练习
cojs 173. 词链 ★☆ 输入文件:link.in 输出文件:link.out 简单对比时间限制:1 s 内存限制:128 MB [问题描述]给定一个仅包含小写字母的英文单词表, ...
- [cf453e]Little Pony and Lord Tirek
来自FallDream的博客,未经允许,请勿转载,谢谢. 更博客= = 有n个数,每个数字都有一个初始大小ai和最大值mi,然后每秒会增加ri,你需要回答m个发生时间依此增大的询问,每次询问区间和并且 ...
- hdu2795 线段树 贴广告
Billboard Time Limit: 20000/8000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total ...
- django rest-framework 4.REST的认证和权限
目前,我们的API对谁可以编辑或删除代码段没有任何限制.我们想要一些更先进的行为,以确保:(这段话抄自官网) 代码段始终与创建者相关联. 只有身份验证的用户可以创建片段. 只有片段的创建者可以更新或删 ...