JavaWeb study notes (xviii) SpringMVC upload files

About file uploading need two jar package
Here Insert Picture Description
The setting of file upload form form
Here Insert Picture Descriptionmethod: post mode must be set, as get request url parameter on the back, behind the carrying and url parameter is limited.
enctype: must be set to "multipart / form-data", form the default form in the form of key-value pairs.

1. The traditional way to upload files

Traditional file upload process:

  1. The browser to select the file to upload
  2. Background receives the request, parses
  3. After parsing decision whether to upload items
  4. If the item is uploaded, upload
    the code
    Here Insert Picture Description

2. SpringMVC upload files

SpringMVC dispacherServlet employed utilizing multiple parsers to improve development efficiency, the file upload function, a file upload SpringMVC provides the CommonsMultipartResolver parser, through this class, the browser may parse the request to upload a file, the user upload request this parsing is omitted a process to improve the development efficiency.
Here Insert Picture Description

  1. Upload interface
<--! 注意这里的name值,必须与后面处理上传请求的方法接收的参数相同 !-->
 <form action="file/fileupload2" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload"><br>
        <input type="submit" value="上传" >
    </form>
  1. Upload the configuration file parser
<!--    这里的bean的id 必须为 multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--这里还可以设置一些参数,如:文件上传大小的限制 -->
    </bean>
  1. Processing method uploads
    @RequestMapping("/fileupload2")
    public String fileUpload2(HttpServletRequest request, MultipartFile upload) throws Exception {

        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        File file = new File(path);
        if (!file.exists()){
            file.mkdir();
        }
        // 获得到文件名
        String filename = upload.getOriginalFilename();
        filename = UUID.randomUUID().toString().replace("-","") + filename;
        // 进行上传文件,上传结束之后,会自动删除掉临时文件
        upload.transferTo(new File(path,filename));
        return "success";
    }

Upload find efficient than the traditional way a lot, SpringMVC file upload parser has been resolved to help users upload request.

Published 66 original articles · won praise 26 · views 10000 +

Guess you like

Origin blog.csdn.net/Time__Lc/article/details/93464939