Spring MVC realizes file 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.
<form action="" enctype="multipart/form-data" method="post">
   <input type="file" name="file"/>
   <input type="submit">
</form>

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.

File upload

1. Import the jar package uploaded by the file, commons fileUpload, and Maven will automatically help us import his dependent package commons IO package;

<!--File upload-->
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>
<!--servlet-api Import a higher version of-->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
</dependency>

2. 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"/>
</bean>

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

3. Write front page

<form action="/upload" enctype="multipart/form-data" method="post">
 <input type="file" name="file"/>
 <input type="submit" value="upload">
</form>

4,Controller

package com.kuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class FileController {
   //@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
   @RequestMapping("/upload")
   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()){
           realPath.mkdir();
      }
       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){
           os.write(buffer,0,len);
           os.flush();
      }
       os.close();
       is.close();
       return "redirect:/index.jsp";
  }
}

5. Test upload file, OK!

Use file To save the uploaded file

1. Write Controller

/*
* Use file To save the uploaded file
*/
@RequestMapping("/upload2")
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()){
       realPath.mkdir();
  }
   //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";
}

2. Front end form submission address modification

3. Visit submit test, OK!

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)

Code implementation:

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
   //Address of the picture to download
   String  path = request.getServletContext().getRealPath("/upload");
   String  fileName = "Basic grammar.jpg";

   //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
   response.setHeader("Content-Disposition",
           "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);
       out.flush();
  }
   out.close();
   input.close();
   return null;
}

front end

<a href="/download">Click download</a>

Test, file download OK

Keywords: Java Front-end server Spring MVC

Added by eflopez on Fri, 25 Feb 2022 18:59:23 +0200