Servlet 3.0 文件上传新特性

Servlet 3.0 实现了文件上传的功能,通过注解的方式指定Servlet的处理请求类型。实现代码如下。
@WebServlet("/UploadFileServlet")
@MultipartConfig(location="E:/test/", maxFileSize = 5*1024*1024)
public class UploadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		Part photo = request.getPart("photo");
		photo.write("001.jpg");
		String h = photo.getHeader("content-disposition");

		System.out.println(h);
		response.getWriter().write("upload success.");
		
		// 多文件上传
		Collection<Part> files = request.getParts();
		for (Part part : files) {
	            String fileName = System.currentTimeMillis() + ".jpg";
	            part.write("upload/" + File.separator + fileName);
	    }
	}

}

你可能感兴趣的:(javaee)