Servlet3.0文件上传

Servlet3.0可以使用注解,而且文件上传也比以前简单多了。

代码如下:

/**
 * 文件上传
 */
@MultipartConfig
@WebServlet(name = "UploadServlet", urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
 
    private static final long serialVersionUID = 1L;
     
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // request.getPart("file"); // 单个文件file是input的name
        Collection<Part> parts = request.getParts(); // 多个文件
        for (Part part : parts) {
            part.write("文件路径");
        }
    }
 
}

注意Servlet上面的注解MultipartConfig,没有会提示以下错误:

Unable to process parts as no multi-part configuration has been provided

另外如果你需要获取文件名称,可以使用下列代码,然后自己处理一下:

String header = part.getHeader("content-disposition");

注:别忘记表单类型enctype="multipart/form-data"