Android实现模拟表单上传
很久以前,写过一篇关于下载的文章:基于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实现模拟表单上传的更多相关文章
- java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例
java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例HttpClient 测试类,提供get post方法实例 package com.zdz.httpclient; i ...
- Netty学习笔记(一):接收nodejs模拟表单上传的文件
好久不写博客了,也好久不写代码了,这两天临时遇上一个事情,觉得不难,加上觉得手有些生,就动手做了一下,结果遇上了不少坑,有新坑,有老坑,痛苦无比,现在总算差不多了,赶紧记录下来,希望以后不再重复这种痛 ...
- php Socket模拟表单上传文件函数_学习
模拟上传文件的php代码 里面访问地址.主机.上传文件名.内容.分隔符可以修改 function postFile($file) { $clf = "\r\n"; ...
- HttpClient(五)-- 模拟表单上传文件
1.maven依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId ...
- 使用CURL模拟表单上传文件
//以下代码适合PHP7.x PHP5.6$file = new CURLFile('./127.zip','application/octet-stream');$file->setMimeT ...
- PHP CURL 模拟form表单上传遇到的小坑
1:引用的时候 $parans ['img']=new \CURLFile($param); 传入的文件 在PHP版本5.5以上记得new CURLFile 不然会上传不成功 /** * http p ...
- 一般处理程序上传文件(html表单上传、aspx页面上传)
html 表单上传文件 一般处理程序由于没有 apsx 页面的整个模型和控件的创建周期,而比较有效率.这里写一个用 html 表单进行文件上传的示例. 1. 表单元素选用 ...
- 相册选择头像或者拍照 上传头像以NSData 图片二进制格式 表单上传
一.点击头像图片 或者按钮 在相册选择照片返回img,网络上传头像要用data表单上传 (1)上传头像属性 // 图片二进制格式 表单上传 @property (nonatomic, strong) ...
- [转]html5表单上传控件Files API
表单上传控件:<input type="file" />(IE9及以下不支持下面这些功能,其它浏览器最新版本均已支持.) 1.允许上传文件数量 允许选择多个文件:< ...
随机推荐
- 学习python的第一个小目标:通过requests+xlrd实现简单接口测试,将测试用例维护在表格中,与脚本分开。
小白的学习方式:通过确定一个小目标来想办法实现它,再通过笔记来加深印象. 面对标题中的小目标我陷入了思考....嗯,首先实现利用xlrd库来取出想要的用例 首先用表格准备好用例,如图下: 先试下取nu ...
- [认证授权] 4.OIDC(OpenId Connect)身份认证授权(核心部分)
0 目录 认证授权系列:http://www.cnblogs.com/linianhui/category/929878.html 1 什么是OIDC? 看一下官方的介绍(http://openid. ...
- FreeMarker标签
目前最流行的两种模板技术恐怕要算freemarker和velocity了,webwork2.2对两者都有不错的支持,也就是说在webwork2中你可以随意选择使用freemarker或velocity ...
- 红包项目总结---MVC版
起因: 针对传统版的明显缺陷做优化.主要是提升可维护性. 效果 线上: 未发布 线下:http://10.27.5.1/svn/FED/code/hongbao/year-end hb-fac ...
- ocr智能图文识别 tess4j 图文,验证码识别 分享及所遇到的问题
自己对tess4j的使用总结 1,tess4j 封装了 tesseract-ocr 的操作 可以用很简洁的几行代码就实现原本tesseract-ocr 复杂的实现逻辑 如果你也想了解tesseract ...
- 关于oracle数据库备份还原-impdp,expdp
初始化: -- 创建表空间 CREATE TABLESPACE 表空间名 DATAFILE '文件名.dat' SIZE 100M AUTOEXTEND ON NEXT 10M MAXSIZE UNL ...
- 每天一个JS 小demo之新建文件夹。主要知识点:DOM方法的综合运用
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"& ...
- 最近一个刚刚毕业的朋友说,他面试时候,遇到最频繁的css问题就是垂直居中,这里给出几种垂直居中方式!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- ZooKeeper数据模型
ZooKeeper有一个分层的命名空间,类似分布式文件系统.它们唯一的区别就在于在命名空间中每个节点可以有数据关联作为它们的子节点.这就像有一个文件系统允许文件也作为文件目录.节点路径通常表示为规范的 ...
- Bash内置命令exec和重定向
Bash内置命令exec可以替换当前程序而不需要启动一个新的进程,可以改变标准输入和输出而不需要启动一个新的子进程.如果文件用exec打开,read命令就会把文件指针每次指向下一行直到文件的末尾,如果 ...