Implement file upload and download function

Let’s first look at the three elements of file upload:

  1. Form submission method: post (get method submission has size limit, post does not)
  2. Form's enctype attribute: must be set to multipart/form-data
  3. The form must have a file upload item: file

File upload introduction

To receive the files uploaded by the client page, the server usually uses two components of Apache:

  • commons-fileupload
  • commons-io

The Spring framework encapsulates the file upload in the spring-web package, which greatly simplifies the server-side code. We only need to declare a parameter of type MultiparFile in the Controller method to receive the uploaded file, for example:

Code

/**
 * @author JUNHAO
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * File Upload
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R<String> upload(MultipartFile file) {

        // Get the original filename of the uploaded file
        String originalFilename = file.getOriginalFilename();
        // Get the suffix of the original filename
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // Use UUID to regenerate file names to prevent file overwriting due to repeated file names
        String fileName = UUID.randomUUID().toString() + suffix;

        try {
            // file is a temporary file and needs to be dumped to the specified location, otherwise the temporary file will be deleted after the request is completed
            // basePath is the specified save path, we declared an attribute above, and the attribute value is read from the yml configuration file for modification
            // There may be IO exceptions here, we need to throw them out
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
reggie:
  path: D:\

Expand your knowledge:

lastIndexOf() method: returns the index of the last occurrence of the specified character in this string, or -1 if there is no such character in this string

substring() method: the parameters in parentheses are different, and the effect will be very different

  • xx.substring(0,2) means to take the first and second characters (left open and right closed) and return a new string
  • xx.substring(2) means remove the first two characters and return a new string

problem found

If we say, we modified the attribute of path in the yml configuration file

reggie:
  path: D:\images\

But our D drive does not have the images folder at all, so we need to add a judgment. If this directory structure does not exist, we will create one

Code:

/**
 * @author JUNHAO
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * File Upload
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R<String> upload(MultipartFile file) {

        // Get the original filename of the uploaded file
        String originalFilename = file.getOriginalFilename();
        // Get the suffix of the original filename
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // Use UUID to regenerate file names to prevent file overwriting due to repeated file names
        String fileName = UUID.randomUUID().toString() + suffix;
        
        
        // Create a directory object
        File dir = new File(basePath);
        // Check if the current directory exists
        if (!dir.exists()) {
            // The directory does not exist, it needs to be created
            dir.mkdirs();
        }
        
        
        try {
            // file is a temporary file and needs to be dumped to the specified location, otherwise the temporary file will be deleted after the request is completed
            // basePath is the specified save path, we declared an attribute above, and the attribute value is read from the yml configuration file for modification
            // There may be IO exceptions here, we need to throw them out
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

This method has a return value, but we are returning null; what value is it appropriate to return? Actually we need to return the file name. After the user uploads the file, there will be a save operation. We need to save the file name to the database, so we need to return the file name to the front end.

document dowload

File download, also known as download, refers to the process of transferring files from a server to a local computer

File download through a browser, usually in two forms:

  • Download as an attachment, pop up a save dialog box, save the file to the specified disk directory
  • Open directly in the browser

File download through the browser is essentially the process of the server writing the file back to the browser in the form of a stream.

1. Open directly in the browser

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-zMg0PsEK-1652449323476)(img/image-20220513211054474.png)]

Judging from the request sent by the front end, the front end has passed a name, and we need to receive this name

/**
 * document dowload
 * @param name
 * @param response
 */
@GetMapping("download")
public void download(String name, HttpServletResponse response) {

}

Why do we need response, because our output stream needs to be obtained through response

/**
 * document dowload
 * @param name
 * @param response
 */
@GetMapping("download")
public void download(String name, HttpServletResponse response) {
    try {
        // Input stream, read file content through input stream
        FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
        // Output stream, write the file back to the browser through the output stream, and display the image in the browser
        ServletOutputStream outputStream = response.getOutputStream();
        // Set the file format of the response to the client
        response.setContentType("image/jpeg");
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        // close resource
        outputStream.close();
        fileInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

end...

Tags: Java Spring programming language

Posted by jdc44 on Sat, 14 May 2022 00:38:50 +0300