javaweb-servlet3.0 文件上传实现

servlet3.0 直接提供了上传的组件 使用十分便捷
首先,在要进行上传的servlet文件写上注解

@MultipartConfig

表示这个servlet文件要进行文件上传
前台form表单要修改 enctype="multipart/form-data"

jsp代码:

${error }

servlet代码:

@WebServlet("/user")
@MultipartConfig
public class UserServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

    

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String method = request.getParameter("method");
        if("save".equals(method)){
            this.userSave(request, response);
        }else{
            request.setAttribute("mainPage", "userJSP/userInfo.jsp");
            request.getRequestDispatcher("mainTemp.jsp").forward(request, response);
        }
    }
    
    protected void userSave(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得上传的文件
        Part part = request.getPart("imagefile");
        System.out.println("submitName:"+part.getSubmittedFileName());
//判断是否上传文件
        if(StringUtil.isNotEmpty(part.getSubmittedFileName())){
//获得上传文件的头信息
            String contentDesc = part.getHeader("content-disposition");
            System.out.println("content-disposition"+ contentDesc);
//上传文件名称包括后缀
            String submitName = part.getSubmittedFileName();
            System.out.println("submitName:"+submitName);
            System.out.println("此文件的大小:"+part.getSize()+"
"); System.out.println("此文件类型:"+part.getContentType()+"
"); //把文件写到这个路径下 String filePath = PropertiesUtil.getValueForKey("imagePath")+imageName+submitName; part.write(filePath); } }

你可能感兴趣的:(javaweb-servlet3.0 文件上传实现)