本案例是利用Servlet3的part完成文件上传功能
单个文件上传
前端页面
<!doctype html>
<html lang="zh">
<head>
<title>单个文件上传demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="upload" enctype="multipart/form-data" method="post">
文件<input type="file" name="file"/><br/>
<input type="submit" name="upload" value="上传"/>
</form>
</body>
</html>注意:enctype要设置为multipart/form-data
Java相关类(利用Servlet上文文件)
@WebServlet("/upload")
// MultipartConfig标识为支持文件上传,location为上传文件的绝对路径@MultipartConfig(location = "C:\\Users\\admin\\Desktop\\upload")public class uploadFileServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=UTF-8"); // 获取请求项,封装成part对象 Part part = req.getPart("file"); // 获取上传文件名 String filename = part.getSubmittedFileName(); // 上传文件 part.write(filename); resp.getWriter().write("文件上传成功"); }}多个文件上传
前端页面
<!doctype html><html lang="zh"><head> <title>多文件上传demo</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body><form action="multiUpload" enctype="multipart/form-data" method="post"> 文件1<input type="file" name="file1"/><br/> 文件2<input type="file" name="file2"/><br/> <input type="submit" name="upload" value="上传"/></form></body></html>Java相关类
@WebServlet("uploadMulti")@MultipartConfig(location = "C:\\Users\\admin\\Desktop\\upload")public class uploadMultiFileServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); if(req.getContentType() == null || !req.getContentType().startsWith("multipart/form-data")) { resp.getWriter().write("错误:http请求的ContentType必须为multipart.form-data"); return; } List<String> fileNames = new ArrayList<>(); req.getParts().stream() .filter(part -> part.getSubmittedFileName() != null && !part.getSubmittedFileName().equals("")) .forEach(part -> { try { // 上传文件 part.write(part.getSubmittedFileName()); fileNames.add(part.getSubmittedFileName()); } catch (IOException e) { e.printStackTrace(); } }); if (fileNames.size() < 1) { resp.getWriter().write("文件上传失败"); return; } resp.getWriter().write(String.join(",",fileNames)+"文件上传成功"); }}tips:本案例学习来源于学校实训