Servlet 文件上传
以下是简单的完整示例:
Servlet 可以通过 HTML 的 <form> 和 2个第3方库
commons-fileupload、commons-io 来完成,在程序运行时确保这2个依赖库引入到 WEB-INF/lib 中;
以下是这两个库的下载地址:
upload.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload File</title>
</head>
<body>
<form method="POST" action="uploadFile" enctype="multipart/form-data">
<label>Choose File: </label><input type="file" name="file" /><br/>
<input type="submit" name="submit" value="upload">
</form>
</body>
</html>
UploadFileServlet.java
public class UploadFileServlet extends HttpServlet {
private static final String UPLOAD_DIR = "upload"; //上传保存目录
private static final int MEMORY_HRESHOLD = 1024 * 1024 * 3 ; //传输内存使用上限 ,超过后将临时文件储存在临时目录中3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40 ; //文件大小上限 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50 ; //请求大小上限 50MB
/*上传数据,保存文件*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
//检测文件是否为多媒体上传,如果不是则停止
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter out = response.getWriter();
out.println("Error: form must include enctype=multipart/form-data");
out.flush();
return ;
}
//设置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_HRESHOLD); //设置内存临界值
factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //设置临时储存目录
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE); //设置文件大小上限
upload.setSizeMax(MAX_REQUEST_SIZE); //设置请求大小上限
upload.setHeaderEncoding("UTF-8");
//文件上传过程
String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIR; //构造临时路径来储存上传文件
File uploadDir = new File(uploadPath);
if(!uploadDir.exists())
uploadDir.mkdir();
try{
@SuppressWarnings("unchecked")
//解析请求的内容,提取文件数据
List<FileItem> formItems = upload.parseRequest(request);
if(formItems != null && formItems.size() > 0){
for(FileItem item : formItems){ //迭代表单数据
if(!item.isFormField()){ //不在表单中的字段,即为上传文件数据所在的FileItem
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile); //保存文件到硬盘
request.setAttribute("message","Upload file successfully");
}
}
}
}catch(Exception ex){
request.setAttribute("message","Error: " + ex.getMessage());
}
//跳转到 massage.jsp
request.getServletContext().getRequestDispatcher("/message.jsp").forward(request,response);
}
}
message.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>Upload file message</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>uploadFile</servlet-name>
<servlet-class>control2.UploadFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadFile</servlet-name>
<url-pattern>/uploadFile</url-pattern>
</servlet-mapping>
</web-app>