Servlet 文件上传
基本上大多数系统都需要用到文件上传,所以了解 Servlet 文件上传很有必要。
1. 上传表单页面
在界面上用 HTML 或 JSP 编写上传表单,表单必须满足:
method="post"enctype="multipart/form-data"
示例 upload.jsp / upload.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Servlet上传文件测试</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>Servlet上传文件测试</h1>
<form method="post" action="/UploadServlet" enctype="multipart/form-data">
文件选择:<br /> <input type="file" name="uploadFile" /> <br />
<br /> <input type="submit" value="上传" />
</form>
</body>
</html>Code language: HTML, XML (xml)
关键点:
enctype="multipart/form-data"表示表单数据按二进制分块方式提交,普通request.getParameter()取不到文件字段。
2. 依赖包
Servlet 文件上传通常借助 Apache Commons 组件实现,需要两个 jar 包:
commons-fileupload-x.x.x.jarcommons-io-x.x.jar
下载地址:
- Commons IO:http://commons.apache.org/proper/commons-io/download_io.cgi
- Commons FileUpload:http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi
将下载后的 jar 放到:
- 项目
WEB-INF/lib目录下 - 若 Tomcat 全局可用,也可放到 Tomcat 的
lib目录
3. 说明补充
使用 Commons FileUpload 时,核心思路是:
- 通过
ServletFileUpload.isMultipartContent(request)判断是否为文件上传请求 - 使用
DiskFileItemFactory创建临时文件/缓存策略 - 使用
ServletFileUpload.parseRequest(request)解析请求,得到List<FileItem> - 遍历
FileItem:- 普通表单字段:
item.isFormField() == true - 文件字段:
item.isFormField() == false,再用item.getName()取文件名,item.getInputStream()或item.write(file)保存文件
- 普通表单字段:
如果你继续贴 UploadServlet 的代码,我可以按前面约定「不改内容、只整理格式」接着整理成规范文档。
要不要我先把「Commons FileUpload 上传 Servlet 标准写法 + 保存路径/中文文件名/大小限制/临时文件」这部分也整理进文档?
Previous: Servlet 中使用 JDBC 连接 MySQL 数据库