MultipartFile realizes file upload and download

Posted by Gmunky on Fri, 10 Dec 2021 09:59:13 +0100

MultipartFile is a tool class provided by spring MVC to simplify upload operations. Before the framework is not used, the native HttpServletRequest is used to receive the uploaded data. The File is passed to the back end as a binary stream, and then we need to convert it into a File class,

In the Spring framework, the support for file upload and download is realized through the MultipartFile interface. A MultipartFile represents a file transmitted from the client, and a MultipartFile [] array represents multiple files transmitted from the client. This is very useful in realizing multi file upload. Of course, through this interface, You can get some basic information of the file transmitted from the client, such as file name, file size, etc Of course, you can also ask Spring to limit the size and type of files transmitted from the client (such as picture file png or text file txt), but the implementation configuration of these functions is not within the scope of this article.

File upload

Import dependency

<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.3</version>
</dependency>

Springboot upload file limit. In actual project development, it is necessary to limit the size of files uploaded by users, so as to ensure that the resources of the server are not wasted. Modify application Properties configuration file, as follows:

# Enable http upload
spring.servlet.multipart.enabled=true
# Set the size limit of a single upload file supported
spring.servlet.multipart.max-file-size=10MB
# Set the maximum request file size and the overall request size
spring.servlet.multipart.max-request-size=20MB
# When the uploaded file reaches the specified configuration amount, the file content is written to the disk
spring.servlet.multipart.file-size-threshold=512KB
# Set temporary directory for upload
spring.servlet.multipart.location=/

For the upload restriction of Springboot upload files, Bean can also be used to achieve the same effect, and the implementation code is as follows:

@Configuration
public class UploadConfig {
 
     @Bean
     public MultipartConfigElement getMultipartConfig() {
         MultipartConfigFactory config = new MultipartConfigFactory();
         // Set a single size limit for uploaded files
         config.setMaxRequestSize(DataSize.parse("10MB"));
         // Set the total upload size limit
         config.setMaxRequestSize(DataSize.parse("100MB"));
         // Set temporary save directory
         config.setLocation("/");
         // Create an upload configuration and return
         return config.createMultipartConfig();
     } 
}

 

Single file upload

The file upload form is a little different from the ordinary form, that is, the attribute enctype = "multipart / form data" needs to be added, which implies that the form has file upload. In addition, the value of the name attribute of the < input / > tag must be consistent with the MultipartFile parameter name of the back-end interface, that is, all files

<form action="/upload" method="POST" enctype="multipart/form-data">
    <input  name="file" type="file"/>
    <button type="submit">Upload file</button>
</form>
 	/**
     * File upload
     * @param file Upload file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) {
        if(file.isEmpty()){
            return "The file is empty";
        }
        System.err.println("The file size is:" + file.getSize());
        System.err.println("The media type of the file is: " + file.getContentType());
        System.err.println("The file name is: " + file.getOriginalFilename());
        
        // Set file storage path
        String filePath = "C:\\Users\\YG\\Desktop\\";
        String uploadFilePath = uploadFile(file, filePath);
        if (!StrUtil.isBlank(uploadFilePath)){
            return "Upload succeeded: "+uploadFilePath;
        }
        return "Upload failed";
    }

    
   /**
     * File upload tool class
     * @param file
     * @param filePath
     * @return
     */
    private String uploadFile(MultipartFile file, String filePath){
        // Get file name
        String fileName = file.getOriginalFilename();
        // Get the date and splice it into the file name to avoid duplicate file names
        String today = DateUtil.today();
        File newFile = new File(filePath, today + fileName);
        // Detect whether the directory exists
        if (!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        try {
            // write file
            file.transferTo(newFile);
            return filePath+today+fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

Multi file upload

Principle: on the basis of single file upload, replace MultipartFile with array MultipartFile [], and cycle through it.

If the accepted parameter is HttpServletRequest request

<!--Multi file upload-->
<form action="/uploadBatch" method="post" enctype="multipart/form-data">
  <p>Document 1:<input type="file" name="file"/></p>
  <p>Document 2:<input type="file" name="file"/></p>
  <p><input type="submit" value="Batch upload"/></p>
</form>
	/**
     * Upload multiple files
     * @param request
     * @return
     */
    @PostMapping("/uploadBatch")
    @ResponseBody
    public String uploadBatch(MultipartHttpServletRequest request){
        List<MultipartFile> files = request.getFiles("file");
        String filePath = "C:\\Users\\YG\\Desktop\\";
        for (int i = 0; i < files.size(); i++){
            MultipartFile file = files.get(i);
            if (!file.isEmpty()){
                uploadFile(file, filePath);
                System.out.println("The first "+i+" Files uploaded successfully");
            }else {
                System.out.println("The first "+i+" Failed to upload files");
            }
        }
        return "Upload succeeded";
    }

If you upload multiple files, you need to add multiple="multiple" in the input of the form. (multiple files can be selected at one time)

The multiple attribute of the < input / > tag of html file is multiple="multiple", which indicates that multiple file selection is supported. At the same time, as for single file upload, the name attribute of our < input / > tag must be the same as the MultipartFile [] parameter name on the back end, that is, files

<form action="/download" enctype="multipart/form-data" method="post">
        <input  name="files" type="file" multiple="multiple" value="Please select multiple files"/>
        <button type="submit">multi submit second</button>
</form>
	/**
     * Upload multiple files
     * @param request
     * @return
     */
    @PostMapping("/uploadBatch")
    @ResponseBody
	public boolean multiFile(MultipartFile[] files) throws IllegalStateException, IOException {
    if(files.length == 0) {
        return false;
    }
    File file = null;
    String filePath = "C:\\Users\\YG\\Desktop\\";
    for (int i = 0; i < files.length; i++) {
        System.err.println("The first" + i + "The size of the files is" + files[i].getSize());
        System.err.println("The first" + i + "Are the files empty" + files[i].isEmpty());
        System.err.println("The first" + i + "The media type of files is" + files[i].getContentType());
        System.err.println("The first" + i + "The file names of the files are" + files[i].getName());
        System.err.println("The first" + i + "The source file name of the files is" + files[i].getOriginalFilename());
        file = new File(path + files[i].getOriginalFilename());
        files[i].transferTo(file);
    }
    return false;
}

To upload a folder, add WebKit directory to the form input. (only folders can be selected, and the files in the folder can be uploaded successfully)

<form action="/upload" method="POST" enctype="multipart/form-data">
    <input  name="file" type="file" multiple="multiple" webkitdirectory directory/>
    <button type="submit">Upload file</button>
</form>

Download File

Downloading a file means that the program reads the file stream and then responds to the client (output stream operation)

<a href="/download">download</a>
 	/**
     * File download
     * @param response
     * @return
     */
    @RequestMapping("/download")
    @ResponseBody
    public String download(HttpServletResponse response){
        String fileName = "QQ.png";
        if (!StrUtil.isBlank(fileName)){
            //Set file path
            File file = new File("C:\\Users\\YG\\Desktop\\QQ.png");
            if (file.exists()){
                // Set forced download not to open
                response.setContentType("application/force-download");
                // Set file name
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                byte[] buff = new byte[1024];
                BufferedInputStream bis = null;
                OutputStream os = null;
                try {
                    os = response.getOutputStream();
                    bis = new BufferedInputStream(new FileInputStream(file));
                    int i = bis.read(buff);
                    while (i != -1) {
                        os.write(buff, 0, buff.length);
                        os.flush();
                        i = bis.read(buff);
                    }
                    return "Download succeeded!";
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "Download failed!";
    }

Topics: Java Spring