想要实现servlet3.0的方式上传文件需要引入以来
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
引入依赖后,开始编写,编写servlet文件
它会自动生成@WebServlet()
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 javax.swing.*; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; @WebServlet(name = "UploadServlet",urlPatterns="/UploadServlet") @MultipartConfig public class UploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //存储路径 “/upload文件夹需要你事先拥有,如idea中找到上传文件需要到target下的目录中” String savePath = request.getServletContext().getRealPath("/upload"); //获取上传的文件集合 Collection<Part> parts = request.getParts(); //上传单个文件 if (parts.size()==1) { Part part = request.getPart("file"); String header = part.getHeader("content-disposition"); System.out.println(header); //获取文件名 String fileName = getFileName(header); System.out.println(fileName); //把文件写到指定路径 part.write(savePath+ File.separator+fileName); }else { //一次性上传多个文件 for (Part part : parts) {//循环处理上传的文件 String header = part.getHeader("content-disposition"); //获取文件名 String fileName = getFileName(header); //把文件写到指定路径 part.write(savePath+File.separator+fileName); } } PrintWriter out = response.getWriter(); JOptionPane.showMessageDialog(null, "上传成功!"); out.println("上传成功"); out.flush(); out.close(); } public String getFileName(String header) { String[] tempArr1 = header.split(";"); String[] tempArr2 = tempArr1[2].split("="); String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"", ""); return fileName; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
其中urlPatterns 指的是你引用该servlet的名称,也就是action提交的路径
<%@page language="java" pageEncoding="UTF-8" isELIgnored="false" %> <html> <head> <title>Servlet3.0实现文件上传</title> </head> <body> 上传单个文件 <form action="/UploadServlet" method="post" enctype="multipart/form-data"> 上传文件:<input type="file" name="file"><br> <input type="submit" value="上传"> </form> <hr /> 上传多个文件 <form action="/UploadServlet" method="post" enctype="multipart/form-data"> 上传文件:<input type="file" name="file1"><br> 上传文件:<input type="file" name="file2"><br> <input type="submit" value="上传"> </form> </fieldset> </body> </html>
然后通过此方法即可上传成功。