很久以前,写过一篇关于下载的文章:基于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. js for循环 等腰三角形demo

    <script> for(var i=1;i<10;i++){ for(var j=1;j<10-i;j++){document.write(" ")} f ...

  2. Asp.Net生命周期的详解

    一.Asp.Net页面生命周期的概念 当我们在浏览器地址栏中输入网址,回车查看页面时,这时会向服务器端IIS)发送一个request请求,服务器就会判断发送过来的请求页面,当完全识别 TTP页面处理程 ...

  3. HTML5 Web Worker简单使用

    Web Workers 是 HTML5 提供的一个javascript多线程解决方案,我们可以将一些大计算量的代码交由web Worker运行而不冻结用户界面. 一:如何使用Worker Web Wo ...

  4. WPF中实现类智能感知

    首先要做的事情就是定义一个popup来显示我们需要展示的东西 <Popup x:Name=" StaysOpen="False" Placement="B ...

  5. orcale设置自增列

    create sequence SEQ_ERRORID minvalue 1 maxvalue 99999999 start with 1000 increment by 1 nocache orde ...

  6. git 知识点汇总

    git commit git commit 命令执行后, git 主要执行了三个操作: 为每一个文件生成一个快照 每一个文件其实是真的数据, 所以 git 会把整个文件内容转成二进制, 然后经过压缩直 ...

  7. 盒子模型,定位技术,负边距,html5 新增标签

    盒子模型 /*[margin 外边距] margin属性最多四个 1.只写一个值,四个方向的margin均为这个值 2.写两个值:上,右两个方向,下默认=上,右 默认=左 3.写三个值:上.右.下三个 ...

  8. jquery移出select指定option

    $("#selectLine option[value!='']").remove();

  9. PHP大批量插入mysql数据库的优化

    <?php /** * Created by PhpStorm. * User: hanks * Date: 6/2/2017 * Time: 6:03 PM */ //PHP大批量插入mysq ...

  10. memcached使用文档

    使用memcached进行内存缓存 通常的网页缓存方式有动态缓存和静态缓存等几种,在ASP.NET中已经可以实现对页面局部进行缓 存,而使用memcached的缓存比ASP.NET的局部缓存更加灵活, ...