很久以前,写过一篇关于下载的文章:基于HTTP协议的下载功能实现,今天对于Android上的文件上传,也简单的提两笔。在Android上,一般使用Http 模拟表单或者FTP来进行文件上传,使用FTP协议,可以直接使用Appache的FTPClient,使用方法很简单,不再赘述。这里主要说明一下Http模拟表单上传的实现。

模拟表单上传,其实也很简单,主要需要在Http post 的数据体中构建表单信息(multipart/form),表单数据格式的规范,可以参考REC标准。下面是一个格式示例:

       ...
Content-Type: multipart/form-data; boundary=------WebKitFormBoundaryK7Ck1eEROPVUf1De
       Content-Length: 145000
... ------WebKitFormBoundaryK7Ck1eEROPVUf1De
Content-Disposition: form-data; name="fileKey"; filename="bg_entry.png"
Content-Type: image/png DATA OF FILE
       ------WebKitFormBoundaryK7Ck1eEROPVUf1De--

表单请求重点在两部分:

Header

1.通过Content-Type告知Server这是一个表单提交请求,并声明自己使用的Boundary。Boundary相当于一个分隔符,用于标志表单数据的开始和结束。

2.通过Content-Length告诉本次请求的数据长度,Post Body的长度(包括上传文件长度)。

Body:

1.以Boundary分割表单数据。

2.表单参数相当于简单的Header,一般包括Content-Disposition(文件信息)和Content-Type(数据类型)两个字段。

3.各部分、各字段之间都要以CRLF分割。

4.最后以Boundary加上“--”结束表单请求。

核心代码如下:

    protected String doUpload(HttpURLConnection connection, UploadParam param) throws Exception {
String path = param.getPath();
String fileKey = TextUtils.isEmpty(param.getFileKey()) ? "file" : param.getFileKey();
String fileName = param.getFileName();
String fileType = TextUtils.isEmpty(param.getContentType()) ? MIME_TYPE_ALL : param.getContentType(); DataOutputStream outs = null;
BufferedReader ins = null;
FileInputStream fouts = null;
String response = null;
try {
// Content-Disposition: form-data; name="fileKey"; filename="bg_entry.png"
// Content-Type: image/png
StringBuilder builder = new StringBuilder(buildParams(param.getParams()));
builder.append(getBoundaryPrefixed())
.append(CRLF)
.append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, fileKey, fileName))
.append(CRLF)
.append(HEADER_CONTENT_TYPE).append(fileType)
.append(CRLF)
//Must jump to new line to indicate the beginning of data.
.append(CRLF);
byte[] headBuf = builder.toString().getBytes(CHARSET_UTF8);
//Must jump to new line to indicate the end of data.
byte[] tailBuf = (CRLF + getBoundaryPrefixed() + BOUNDARY_PREFIX + CRLF).getBytes(CHARSET_UTF8);
long currentBytes = 0;
File file = new File(path);
long totalSize = file.length() + headBuf.length + tailBuf.length;
//Generally speaking,Files larger than 4M should use streaming mode.
if (totalSize > 4 * 1024 * 1024) {
//Avoid oom when post large file.Ether way is ok.
connection.setChunkedStreamingMode(1024);
// connection.setFixedLengthStreamingMode(totalSize);
}
connection.setRequestProperty(HEADER_CONTENT_LENGTH, String.valueOf(totalSize));
connection.connect(); outs = new DataOutputStream(connection.getOutputStream());
outs.write(headBuf);
currentBytes += headBuf.length;
updateProgress(currentBytes, totalSize);
fouts = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length = -1;
long startTime = System.currentTimeMillis();
long now = 0;
while ((length = fouts.read(buffer)) != -1) {
if (length > 0) {
outs.write(buffer, 0, length);
currentBytes += length;
now = System.currentTimeMillis();
if (now - startTime >= PROGRESS_RATE) {
updateProgress(currentBytes, totalSize);
startTime = now;
}
}
if (!canRun()) {
throw new Exception("Upload cancelled");
}
}
outs.write(tailBuf);
outs.flush();
updateProgress(totalSize, totalSize); fouts.close();
fouts = null; //Response.
if (connection.getResponseCode() != 200) {
throw new IllegalStateException(String.format("Error upload response: code:%s msg:%s", connection.getResponseCode(), connection.getResponseMessage()));
}
ins = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer b = new StringBuffer();
while ((line = ins.readLine()) != null) {
b.append(line);
if (!canRun()) {
throw new Exception("Upload cancelled");
}
} response = b.toString();
if (TextUtils.isEmpty(response)) {
throw new NullPointerException("Null response: " + response);
}
outs.close();
outs = null;
ins.close();
ins = null;
} finally {
if (fouts != null) {
fouts.close();
fouts = null;
}
if (outs != null) {
outs.close();
outs = null;
}
if (ins != null) {
ins.close();
ins = null;
}
}
return response;
}

主要步凑为:

1.配置Header参数

2.构建表单参数

3.读取和发送文件内容

4.获取响应码

其中值得注意的是,一般情况下,上传会把所有的文件内容读取到内存中再统一发送,如果文件过大,将可能导致内存溢出。所以在判断文件内容大于4MB时,使用Chunked模式或Stream模式来避免OOM。

            if (totalSize > 4 * 1024 * 1024) {
//Avoid oom when post large file.Ether way is ok.
connection.setChunkedStreamingMode(1024);
//connection.setFixedLengthStreamingMode(totalSize);
}

更多代码详情请参考:TransferLibrary——一个Android文件传输库,主要实现基于Http的文件上传和下载,简单方便,支持多任务下载,断点续传等等,欢迎小伙伴们使用交流:D

Android实现模拟表单上传的更多相关文章

  1. java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例

    java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例HttpClient 测试类,提供get post方法实例 package com.zdz.httpclient; i ...

  2. Netty学习笔记(一):接收nodejs模拟表单上传的文件

    好久不写博客了,也好久不写代码了,这两天临时遇上一个事情,觉得不难,加上觉得手有些生,就动手做了一下,结果遇上了不少坑,有新坑,有老坑,痛苦无比,现在总算差不多了,赶紧记录下来,希望以后不再重复这种痛 ...

  3. php Socket模拟表单上传文件函数_学习

    模拟上传文件的php代码 里面访问地址.主机.上传文件名.内容.分隔符可以修改   function postFile($file) {     $clf = "\r\n";   ...

  4. HttpClient(五)-- 模拟表单上传文件

    1.maven依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId ...

  5. 使用CURL模拟表单上传文件

    //以下代码适合PHP7.x PHP5.6$file = new CURLFile('./127.zip','application/octet-stream');$file->setMimeT ...

  6. PHP CURL 模拟form表单上传遇到的小坑

    1:引用的时候 $parans ['img']=new \CURLFile($param); 传入的文件 在PHP版本5.5以上记得new CURLFile 不然会上传不成功 /** * http p ...

  7. 一般处理程序上传文件(html表单上传、aspx页面上传)

    html 表单上传文件        一般处理程序由于没有 apsx 页面的整个模型和控件的创建周期,而比较有效率.这里写一个用 html 表单进行文件上传的示例.        1. 表单元素选用 ...

  8. 相册选择头像或者拍照 上传头像以NSData 图片二进制格式 表单上传

    一.点击头像图片 或者按钮 在相册选择照片返回img,网络上传头像要用data表单上传 (1)上传头像属性 // 图片二进制格式 表单上传 @property (nonatomic, strong) ...

  9. [转]html5表单上传控件Files API

    表单上传控件:<input type="file" />(IE9及以下不支持下面这些功能,其它浏览器最新版本均已支持.) 1.允许上传文件数量 允许选择多个文件:< ...

随机推荐

  1. 偏最小二乘回归分析建模步骤的R实现(康复俱乐部20名成员测试数据)+补充pls回归系数矩阵的算法实现

    kf=read.csv('d:/kf.csv') # 读取康复数据kfsl=as.matrix(kf[,1:3]) #生成生理指标矩阵xl=as.matrix(kf[,4:6]) #生成训练指标矩阵x ...

  2. 可视化之Berkeley Earth

    去年冬天雾霾严重的那几天,写了两篇关于空气质量的文章,<可视化之PM2.5>和<谈谈我对雾霾的认识>.坦白说,环境问题是一个无法逃避又无能为力的话题.最近因为工作中有一些数据可 ...

  3. VR全景:vr元年过后,这些企业如何发动“vr+”应用引擎?

    2016年,VR可谓是四处衍生.从如痴如迷的游戏行业到喜闻乐见的影视行业,再到医疗.军事.房地产,随便呼出一个"+",VR便能左右逢源,VR+各行各业,俨然成为一种标配.最近,Ma ...

  4. 一天搞定CSS:初识css--01

    1)CSS:层叠样式表(英文全称:Cascading Style Sheets) 是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言. C ...

  5. webApi签名验证

    还是一如既往先上结构图如下: 上一讲说明了redis,也谢谢心态的建议.这里经过改进后的redis的地址 当然这里是加密了的,具体实现如下图: 这里提供的解密. 先把加密解密的帮助类放上来. usin ...

  6. Core ML 机器学习

    在WWDC 2017开发者大会上,苹果宣布了一系列新的面向开发者的机器学习 API,包括面部识别的视觉 API.自然语言处理 API,这些 API 集成了苹果所谓的 Core ML 框架.Core M ...

  7. PHPstrom的Disable Power Save Mode

    1.安装好phpstorm之后 发现代码高亮和函数自动提示都失效了 网上有人说可能是Power save mode的原因开始没找到这个设置在哪 后来在底部面板的信息提示处发现有一条系统消息: 17:0 ...

  8. Docker 网络命令

    docker network create docker network connect docker network ls docker network rm docker network disc ...

  9. log4j 在项目中的详细配置

    1.添加log4j 包 2.首先在src目录下添加log4j.properties文件 log4j.rootLogger=debug, stdout, R log4j.appender.stdout= ...

  10. Python模块之ConfigParser - 读写配置文件

    Python 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件. 配置文件的格式 a) 配置文件中包含一个或多个 section, 每个 section 有自己的 opt ...