Upload and download

12. Upload and download

File upload is one of the most common functions in project development. Spring MVC can well support file upload, but MultipartResolver is not installed in the context of spring MVC by default, so it cannot handle file upload by default. If you want to use spring's file upload function, you need to configure MultipartResolver in the context.

Front end form requirements: in order to upload files, the method of the form must be set to POST and the enctype must be set to multipart / form data. Only in this case, the browser will send the file selected by the user to the server as binary data;

Give a detailed description of the enctype attribute in the form:

  • Application / x-www = form urlencoded: by default, only the value attribute value in the form field is processed. Forms with this encoding method will process the value in the form field into URL encoding method.
  • Multipart / form data: this encoding method will process form data in the form of binary stream. This encoding method will also encapsulate the contents of the file specified in the file field into the request parameters, and will not encode characters.
  • text/plain: except for converting spaces into "+" signs, other characters are not encoded. This method is applicable to sending mail directly through forms.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>Upload test files</h1>
<form action="${pageContext.request.contextPath}/upload2" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit">

Once the enctype is set to multipart / form data, the browser will process the form data in the form of binary stream, and the processing of file upload involves parsing the original HTTP response on the server side. In 2003, the Apache Software Foundation released the open source Commons FileUpload component, which soon became the best choice for Servlet/JSP programmers to upload files.

  • Servlet3. The 0 specification has provided a method to handle file upload, but this upload needs to be completed in the servlet.
  • Spring MVC provides a simpler encapsulation.
  • Spring MVC provides direct support for file upload, which is implemented with the plug and play MultipartResolver.
  • Spring MVC implements a MultipartResolver implementation class using Apache Commons FileUpload Technology:
  • CommonsMultipartResolver. Therefore, the file upload of spring MVC also needs to rely on the component of Apache Commons FileUpload.

Import jar package

<!--File upload-->
<!--servlet-api Import a higher version of-->

Configuration bean: multipartResolver

[note!!! The id of this bena must be: multipartResolver, or 400 error will be reported when uploading the file! I've planted a pit here, and I'll teach you a lesson!]

<!--File upload configuration-->
<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- The encoding format of the request must be the same as jSP of pageEncoding Properties are consistent so that the contents of the form can be read correctly. The default is ISO-8859-1 -->
   <property name="defaultEncoding" value="utf-8"/>
   <!-- Upper limit of uploaded file size, in bytes (10485760)=10M) -->
   <property name="maxUploadSize" value="10485760"/>
   <property name="maxInMemorySize" value="40960"/>

Common methods of CommonsMultipartFile:

  • String getOriginalFilename(): get the original name of the uploaded file
  • InputStream getInputStream(): get file stream
  • void transferTo(File dest): save the uploaded file to a directory file

Let's actually test it

//@RequestParam("file") encapsulates the file obtained by the name=file control into a CommonsMultipartFile object
//If you upload CommonsMultipartFile in batch, it can be an array
public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {

    //Get file name: file getOriginalFilename();
    String uploadFileName = file.getOriginalFilename();

    //If the file name is empty, go back to the home page directly!
    if ("".equals(uploadFileName)){
        return "redirect:/index.jsp";
    System.out.println("Upload file name : "+uploadFileName);

    //Upload path save settings
    String path = request.getServletContext().getRealPath("/upload");
    //If the path does not exist, create one
    File realPath = new File(path);
    if (!realPath.exists()){
    System.out.println("Upload file storage address:"+realPath);

    InputStream is = file.getInputStream(); //File input stream
    OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //File output stream

    //Read write
    int len=0;
    byte[] buffer = new byte[1024];
    while ((len=is.read(buffer))!=-1){
    return "redirect:/index.jsp";

Use file To save the uploaded file

     * Use file To save the uploaded file
public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

    //Upload path save settings
    String path = request.getServletContext().getRealPath("/upload");
    File realPath = new File(path);
    if (!realPath.exists()){
    //Upload file address
    System.out.println("Upload file storage address:"+realPath);

    //Write the file directly through the CommonsMultipartFile method (note this time)
    file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));

    return "redirect:/index.jsp";

File download

File download steps:

1. Set response header

2. Read file -- InputStream

3. Write out file -- OutputStream

4. Perform operations

5. Close flow (first on then off)

public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
    //Address of the picture to download

    String  path = request.getServletContext().getRealPath("/upload");
    String  fileName = "3.png";
    System.out.println("path" + path);
    //1. Set response header
    response.reset(); //Set the page not to be cached, and empty the buffer
    response.setCharacterEncoding("UTF-8"); //Character encoding
    response.setContentType("multipart/form-data"); //Binary transmission data
    //Set response header
                       "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));

    File file = new File(path,fileName);
    //2. Read file -- input stream
    InputStream input=new FileInputStream(file);
    //3. Write out file -- output stream
    OutputStream out = response.getOutputStream();

    byte[] buff =new byte[1024];
    int index=0;
    //4. Perform write out operation
    while((index= input.read(buff))!= -1){
        out.write(buff, 0, index);
    return null;
<a href="${pageContext.request.contextPath}/dd">Click download</a>

Keywords: Spring MVC

Added by velkymx on Thu, 10 Mar 2022 13:53:39 +0200