Examples and analysis of spring boot multi file upload code

Time:2021-3-18

This article mainly introduces the spring boot multi file upload code examples and analysis, the article through the example code is very detailed, for everyone’s study or work has a certain reference learning value, need friends can refer to

I. explanation

Spingmvc supports file upload, which is implemented through the Commons multipart resolver of apach’s commons file upload package
Multipart resolver of spingmvc.

The example of this article is a simple multi file upload, which can be modified according to different business.

two pom.xlm


<dependencies>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>

three application.yml

spring:
 servlet:
  multipart:
   Max file size: 200MB # upload size of single file
   Request size ﹥ 600MB

youku1327:
 file:
 root:
  Path: "C: \ \ \ mydata \ \ generator \ \ version06 \ \", storage path

Four controllers

/**
 * @Author lsc
 * @Description <p> </p>
 * @Date 2019/10/2 20:58
 * @Version 1.0
 */
@RestController
public class FileUploadController {

  @Value("${youku1327.file.root.path}")
  private String fileRootPath;

  @PostMapping("/file/upload")
  public String fileUpload(@RequestParam("files")MultipartFile[] files){
    String filePath = "";
    //Multi file upload
    for (MultipartFile file : files){
      //Upload simple file name
      String originalFilename = file.getOriginalFilename();
      //Storage path
       filePath = new StringBuilder(fileRootPath)
          .append(System.currentTimeMillis())
          .append(originalFilename)
          .toString();
      try {
        //Save the file
        file.transferTo(new File(filePath));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return filePath;
  }
}

5. Start up


/**
 * @Author lsc
 * @Description <p> </p>
 * @Date 2019/10/2 20:54
 * @Version 1.0
 */
@SpringBootApplication
public class FileUploadApplication {
  public static void main(String[] args) {
    SpringApplication.run(FileUploadApplication.class,args);
  }
}

Six tests

Send the HTTP post request in the form of a form. The key is files, which should be consistent with the parameter name of multipartfile. Select two files. After sending successfully, you will see the last returned file path;

Open the saved file path to find that the file has been uploaded.

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.