1. 程式人生 > >@MultipartConfig,Servlet3.0通過Part進行檔案上傳

@MultipartConfig,Servlet3.0通過Part進行檔案上傳

@MultipartConfig
使用註解@MultipartConfig 將一個 Servlet 標識為支援檔案上傳。Servlet3.0 將
multipart/form-data 的 POST 請求封裝成 Part,通過 Part 對檔案進行上傳。
Servlet3 沒有提供直接獲取檔名的方法,需要從請求頭中解析出來

upload.html

<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="f">
<br/>
<input
type="submit" name="submit">
</form>

UploadServlet//request.getpart()單檔案上傳

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UploadServlet() {}

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); // 獲取請求項, 封裝成Part物件 Part part = request.getPart("f"); String fileName = part.getSubmittedFileName(); System.out.println(fileName); String direc = this
.getServletContext().getRealPath("/upload/"); File dirf = new File(direc); if(!dirf.exists()){ dirf.mkdirs(); } part.write(direc+fileName); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

使用request.getParts() 多檔案上傳

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        Collection<Part> parts = request.getParts();

        for(Part part:parts){
            String fileName = part.getSubmittedFileName();
            System.out.println(fileName);

            if(null!=fileName&&!(fileName).trim().equals("")){

                String direc = this.getServletContext().getRealPath("/upload/");
                File dirf = new File(direc);

                if(!dirf.exists()){
                    dirf.mkdirs();
                }
                part.write(direc+fileName);
            }

        }