构建multipart/form-data实现文件上传

通常文件上传都是通过form表单中的file控件,并将form中的content-type设置为multipart/form-data。现在我们通过java来构建这部分请求内容实现文件上传功能。

一、关于multipart/form-data

文件上传本质上是一个POST请求。只不过请求头以及请求内容遵循一定的规则(协议)

  • 请求头(Request Headers)中需要设置 Content-Type 为 multipart/form-data; boundary=${boundary}。其中${boundary}分割线,需要在代码中替换,且尽量复杂,不易重复

  • 请求正文(Request Body)需要使用在 Header中设置的 ${boundary}来分割当前正文中的FormItem,内容格式如下

    --${boundary}
    Content-Disposition: form-data; name="id" testCodeUpload
    --${boundary}
    Content-Disposition: form-data; name="file";filename="xx.txt"
    Content-Type: application/octet-stream {{这里写入文件流}}
    --${boundary}--

    正文开始以前缀+${boundary}开始,以 前缀 +${boundary}+前缀结束。中间每个FormItem 以 前缀+${boundary}开始,以一个空白的换行结束。

二、代码实现

实例代码采用HttpURLConnection实现一个简单POST请求

  • 建立http请求,设置基本参数

URL postUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
  • 添加文件上传必须的请求信息,获取http请输出流

String boundary = "----" + UUID.randomUUID().toString();
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
OutputStream out = conn.getOutputStream();
StringBuilder sb = new StringBuilder();
  • 一组FormItem

sb.append(boundaryPrefix);
sb.append(boundary);
sb.append(newLine);
sb.append("Content-Disposition: form-data; name=\"id\"");
sb.append(newLine);
sb.append(newLine);
sb.append("testCodeUpload");
sb.append(newLine);
  • 文件写人

sb.append(boundaryPrefix);
sb.append(boundary);
sb.append(newLine);
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ fileName + "\"");
sb.append("Content-Type: application/octet-stream");
sb.append(newLine);
sb.append(newLine);
out.write(sb.toString().getBytes());
File file = new File(file1);
FileInputStream in = new FileInputStream(file);
byte[] bufferOut = new byte[1024];
int bytes = 0;
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write(newLine.getBytes());
in.close();
  • 结束标志 前缀+boundary +前缀
byte[] end_data = (newLine + boundaryPrefix + boundary + boundaryPrefix + newLine)
.getBytes();
out.write(end_data);
out.flush();
out.close();

三、文件接收

  • 文件接收端通过迭代每个FileItem获取不同的数据

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
items = upload.parseRequest(request);
} catch (FileUploadException ex) {
ex.printStackTrace();
out.println(ex.getMessage());
return;
}
Iterator<FileItem> itr = items.iterator();
String id = "", fileName = "";
int chunks = 1, chunk = 0;
FileItem tempFileItem = null;
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.getFieldName().equals("id")) {
id = item.getString();
} else if (item.getFieldName().equals("name")) {
fileName = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
} else if (item.getFieldName().equals("file")) {
tempFileItem = item;
}

四、总结

通过代码实现一遍文件上传,了解其运行机制,解开了以前在写文件上传代码中item.getFieldName().equals("name")等相关判断的疑惑。所以,对于已有的基础代码,还是多看,多写,多实践。

附完整代码

 @Test
public void buildUploadStream() throws IOException {
String url ="uploadurl";
file1 = "D:\\test.xls";
fileName = "test.xls"; String newLine = "\r\n";
String boundaryPrefix = "--";
String boundary = "----" + UUID.randomUUID().toString(); URL postUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection(); conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false); conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary); OutputStream out = conn.getOutputStream(); StringBuilder sb = new StringBuilder(); sb.append(boundaryPrefix);
sb.append(boundary);
sb.append(newLine); sb.append("Content-Disposition: form-data; name=\"id\"");
sb.append(newLine);
sb.append(newLine);
sb.append("testCodeUpload");
sb.append(newLine); sb.append(boundaryPrefix);
sb.append(boundary);
sb.append(newLine); sb.append("Content-Disposition: form-data; name=\"name\"");
sb.append(newLine);
sb.append(newLine);
sb.append(fileName);
sb.append(newLine); sb.append(boundaryPrefix);
sb.append(boundary);
sb.append(newLine); sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ fileName + "\"");
sb.append("Content-Type: application/octet-stream");
sb.append(newLine);
sb.append(newLine); out.write(sb.toString().getBytes()); File file = new File(file1);
FileInputStream in = new FileInputStream(file);
byte[] bufferOut = new byte[1024];
int bytes = 0;
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write(newLine.getBytes());
in.close();
byte[] end_data = (newLine + boundaryPrefix + boundary + boundaryPrefix + newLine)
.getBytes();
out.write(end_data);
out.flush();
out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}

all code

构建multipart/form-data实现文件上传的更多相关文章

  1. Ajax(form表单文件上传、请求头之contentType、Ajax传递json数据、Ajax文件上传)

    form表单文件上传 上菜 file_put.html <form action="" method="post" enctype="multi ...

  2. jquery.form 兼容IE89文件上传

    导入部分 <script type="text/javascript" src="js/jquery-1.8.3.min.js" charset=&quo ...

  3. 构建基于阿里云OSS文件上传服务

    转载请注明来源:http://blog.csdn.net/loongshawn/article/details/50710132 <构建基于阿里云OSS文件上传服务> <构建基于OS ...

  4. Django 基于Ajax & form 简单实现文件上传

    前端实现 <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="U ...

  5. form表单文件上传提交且接口回调显示提交成功

    前端: <form method="post" enctype="multipart/form-data" id="formSubmit&quo ...

  6. form表单文件上传 servlet文件接收

    需要导入jar包 commons-fileupload-1.3.2.jar commons-io-2.5.jar Upload.Jsp代码 <%@ page language="jav ...

  7. Spring MVC-表单(Form)标签-文件上传(File Upload)示例(转载实践)

    以下内容翻译自:https://www.tutorialspoint.com/springmvc/springmvc_upload.htm 说明:示例基于Spring MVC 4.1.6. 以下示例显 ...

  8. 实用ExtJS教程100例-009:ExtJS Form无刷新文件上传

    文件上传在Web程序开发中必不可少,ExtJS Form中有一个filefield字段,用来选择文件并上传.今天我们来演示一下如何通过filefield实现ExtJS Form无刷新的文件上传. 首先 ...

  9. WebApi实现Ajax模拟Multipart/form-data方式多文件上传

    前端页面代码: <input type="file" class="file_control" /><br /> <input t ...

  10. SSM+form表单文件上传

    这里介绍SSM如何配置上传文件 配置springmvc.xml: <!--配置上传下载--> <bean id="multipartResolver" class ...

随机推荐

  1. VIM系统复制粘贴

    1 需求 系统复制粘贴主要是满足下面两个需求. 在多个对象之间复制粘贴 vim窗口与vim窗口之间 外部界面与vim窗口之间 不变复制粘贴.从外部界面复制粘贴到vim窗口时,文本不发生任何变化. 2 ...

  2. RESTful-4使用教程

    一.REST起源REST(Representational State Transfer)表象化状态转变(表述性状态转变),在2000年被提出,基于HTTP.URI.XML.JSON等标准和协议,支持 ...

  3. DS博客作业01—日期抽象数据类型设计与实现

    1.本章学习总结 1.1 思维导图 1.2学习体会 开学就来了个大作业,还要求用的是c++语法,作为一个只听过没学过的未知语法,靠着CSDN和寝室大佬的帮助下渐渐地了解了一些c++的使用,现在也可以使 ...

  4. windows许可证即将过期

    win+R 输入 slmgr.vbs -xpr 查看日期 激活工具地址: 链接: https://pan.baidu.com/s/1S5nealQM1bytPYV6CYbgyg 提取码: sbmu 1 ...

  5. company_base_info_staff_job

    "company_base_info_staff_job": { "engine": "python script", # datax or ...

  6. 更换MariaDB数据库

    https://downloads.mariadb.org/mariadb/repositories/#mirror=neusoft&distro=Ubuntu&distro_rele ...

  7. window 安装redis、memcache的php扩展和 reidis 、memcache 及 reids管理软件

    redis 1.安装redis的php扩展 http://windows.php.net/downloads/pecl/releases/redis/ http://windows.php.net/d ...

  8. PS2键盘扫描码:通码与断码

    键盘扫描码(实用于标准PC的101.102和104 键的键盘),按下发送通码,弹起发送断码. 说明: 第一类按键,通码为1字节,断码为 0xF0+通码 形式.如A键,其通码为 0x1C,断码为 0xF ...

  9. 安装selenium

    步骤: 1.下载setuptools2.点击安装setuptools.exe3.安装成功后,python的安装目录下会有Scripts的文件夹4.配置环境变量:python安装目录\Scripts5. ...

  10. jquery获取一组文本框的值

    $("#btn5").click(function()  {    var str="";$("[name='checkbox'][checked]& ...