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.允许上传文件数量 允许选择多个文件:< ...
随机推荐
- win10下装mysql-5.7.18-winx64
步骤1 官网下载地址:https://dev.mysql.com/downloads/mysql/ 选择手动安装版: 解压到D盘mysql文件夹下: 比以往的版本里缺少了两个.ini文件,直接copy ...
- 导入数据到mysql服务器上,报错,以及停止的解决办法
两次都是因为磁盘不够,这次得以解决: =>下面是可能会用到的命令行: 1.查看磁盘占用大小: df -hl 发现: 从上面看出来,根目录 / 下的东西沾满了 /dev/sda1 但是 / ...
- python爬虫从入门到放弃(六)之 BeautifulSoup库的使用
上一篇文章的正则,其实对很多人来说用起来是不方便的,加上需要记很多规则,所以用起来不是特别熟练,而这节我们提到的beautifulsoup就是一个非常强大的工具,爬虫利器. beautifulSoup ...
- 用超链接传递数组或get方式
<?php /** * 超链接传递数组参数 */ if($_GET['names']){ $arr=explode('-',$_GET['names']);//将数组分割为字符串 print_r ...
- OVS 中的 upcall 线程
总体概览如下: 假设upcall handler线程有两个,vport有四个,那么每个vport下都将持有两个NetLink连接的信息,这两个NetLink连接将被用来上送upcall消息. 每个Ne ...
- php+mysql 除了设置主键防止表单提交内容重复外的另一种方法
感觉好久没有更新博客了,一直在做网站及后台,也没有遇到让我觉得可以整理的内容,之前做的一个系统,已经完成了,后来客户又要求加一个功能,大概就是表单提交的时候,约束有一项不能和以前的内容重复,如图 比如 ...
- Spring学习(10)--- @Qualifier注解
按类型自动装配可能多个bean实例的情况,可以使用Spring的@Qualifier注解缩小范围(或指定唯一),也可以指定单独的构造器参数或方法参数 可用于注解集合类型变量 例子: package c ...
- Thrift中required和optional
最近在搞Thrift,对其字段声明中的required关键字有所误解,仔细调试了一下才明白其真实含义. required的意思不是说声明对象时,必须填这个值,而是Thrift在传输(序列化)过程中无论 ...
- Redis数据类型之List(三)
前言:list即链表,它是一个能维持数据先后顺序的列表,便于在表的两端追加和删除数据,中间位置的存取具有O(N)的时间复杂度,是一个双向链表. 一.内部原理 redis ...
- 几个常用的linux命令(操作服务器时会用到)
目录 tmux 背景 安装 使用 启动一个tmux session 暂时离开当前session 回到之前的session 重命名session 创建window 创建pane ps scp 参考 tm ...