Servlet3.0 新增了对文件上传请求解析的支持,javax.servlet.http.HttpServletRequest#getParts
,使用request.getParts();
即可获取文件上传包解析后的结果,从此不再需要使用第三方jar来处理文件上传请求了。
2.1 JSP multipart-config
JSP使用request.getParts();
必须配置multipart-config
,否则请求时会报错:Unable to process parts as no multi-part configuration has been provided
(由于没有提供multi-part配置,无法处理parts)。
在web.xml中添加如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>file-upload-parts.jsp</servlet-name>
<jsp-file>/modules/servlet/fileupload/file-upload-parts.jsp</jsp-file>
<multipart-config>
<max-file-size>1000000</max-file-size>
<max-request-size>1000000</max-request-size>
<file-size-threshold>1000000</file-size-threshold>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>file-upload-parts.jsp</servlet-name>
<url-pattern>/modules/servlet/fileupload/file-upload-parts.jsp</url-pattern>
</servlet-mapping>
</web-app>
示例 - file-upload-parts.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="org.apache.commons.io.IOUtils" %>
<%@ page import="java.util.Collection" %>
<%@ page import="java.io.File" %>
<%
String contentType = request.getContentType();
// 检测是否是multipart请求
if (contentType != null && contentType.startsWith("multipart/")) {
String dir = request.getSession().getServletContext().getRealPath("/uploads/");
File uploadDir = new File(dir);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
Collection<Part> parts = request.getParts();
for (Part part : parts) {
String fileName = part.getSubmittedFileName();
if (fileName != null) {
File uploadFile = new File(uploadDir, fileName);
out.println(part.getName() + ": " + uploadFile.getAbsolutePath() + "<br/>");
} else {
out.println(part.getName() + ": " + IOUtils.toString(part.getInputStream()) + "<br/>");
}
}
} else {
%>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>File upload</title>
</head>
<body>
<form action="" enctype="multipart/form-data" method="post">
<p>
用户名: <input name="username" type="text"/>
文件: <input id="file" name="file" type="file"/>
</p>
<input name="submit" type="submit" value="Submit"/>
</form>
</body>
</html>
<%
}
%>
访问示例中的文件上传地址:http://localhost:8000/modules/servlet/fileupload/file-upload-parts.jsp:
文件上传成功:
2.2 Servlet @MultipartConfig
Servlet3.0 需要配置@MultipartConfig
注解才能支持multipart
解析。
示例 - FileUploadServlet代码:
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
@MultipartConfig
@WebServlet(urlPatterns = "/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE html>\n" +
"<html lang=\"zh\">\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>File upload</title>\n" +
"</head>\n" +
"<body>\n" +
"<form action=\"\" enctype=\"multipart/form-data\" method=\"post\">\n" +
" <p>\n" +
" 用户名: <input name=\"username\" type=\"text\"/>\n" +
" 文件: <input id=\"file\" name=\"file\" type=\"file\"/>\n" +
" </p>\n" +
" <input name=\"submit\" type=\"submit\" value=\"Submit\"/>\n" +
"</form>\n" +
"</body>\n" +
"</html>");
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String contentType = request.getContentType();
// 检测是否是multipart请求
if (contentType != null && contentType.startsWith("multipart/")) {
String dir = request.getSession().getServletContext().getRealPath("/uploads/");
File uploadDir = new File(dir);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
Collection<Part> parts = request.getParts();
for (Part part : parts) {
String fileName = part.getSubmittedFileName();
if (fileName != null) {
File uploadFile = new File(uploadDir, fileName);
out.println(part.getName() + ": " + uploadFile.getAbsolutePath());
FileUtils.write(uploadFile, IOUtils.toString(part.getInputStream(), "UTF-8"));
} else {
out.println(part.getName() + ": " + IOUtils.toString(part.getInputStream()));
}
}
}
out.flush();
out.close();
}
}
访问示例中的文件上传地址:http://localhost:8000/FileUploadServlet
文件上传成功: