Spring MVC file download

File download is to download files from the file server to the local. In spring MVC, there are two steps to download files:

Step 1: use a file download hyperlink on the client. The href attribute in the link points to the method and file name of downloading the file in the background;

Step 2: in the background controller class, use the file download method provided by spring MVC to download.

springmvc provides an object of ResponseEntity type, which can be used to easily define the returned HttpHeaders object and HttpStatus object. The configuration information required for downloading files can be completed by setting these two objects. The code of file download is as follows:

  public ResponseEntity<byte[]> downFile(HttpServletRequest request, String filename) throws IOException {

        //Specify the path of the file to download
        String path = request.getServletContext().getRealPath("/upload/");
        //Create the file object
        File file = new File(path + File.separator + filename);
        //Set response header
        HttpHeaders headers = new HttpHeaders();
        //Notify the browser to open the file as a download
        headers.setContentDispositionFormData("attachment", filename);
        //Define to download and return file data in the form of stream
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //Use the ResponseEntity object of spring MVC framework to encapsulate the returned data
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }

Description: in the downFile method, first create a file object according to the file path and the file name to be downloaded, then set the opening method and downloading method of the file in the response header, and finally return the download result object encapsulated by ResponseEntity. MediaType.APPLICATION_OCTET_STREAM means downloading data as a binary stream.

For the Chinese name of the file name garbled processing:

If the file name is in English, the file name will not be garbled, but if the file name is in Chinese, it may be garbled. At this time, the file name needs to be transcoded. As follows:

public ResponseEntity<byte[]> downFile(HttpServletRequest request, String filename) throws IOException {

        //Specify the path of the file to download
        String path = request.getServletContext().getRealPath("/upload/");
        //Create the file object
        File file = new File(path + File.separator + filename);
    
        //Encode the file name to prevent Chinese file names from being garbled
        filename = this.getFilename(request, filename);

        //Set response header
        HttpHeaders headers = new HttpHeaders();
        //Notify the browser to open the file as a download
        headers.setContentDispositionFormData("attachment", filename);
        //Define to download and return file data in the form of stream
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //Use the ResponseEntity object of spring MVC framework to encapsulate the returned data
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }

    /**
     * Encode according to different browser settings
     *
     * @param request  Request object
     * @param filename File name requiring transcoding
     * @return Returns the encoded file name
     * @throws IOException
     */
    public String getFilename(HttpServletRequest request, String filename) throws IOException {

        //Keywords in different versions of IE user agent
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        
        //Get request header proxy information
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE kernel browser, unified for utf-8 coding display
                return URLEncoder.encode(filename, "UTF-8");
            }
        }

        //Firefox and other browsers are displayed in ISO-8859-1 code
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }

The above is the file download content of spring MVC.

Tags: Spring MVC

Posted by timbolt on Wed, 25 May 2022 23:22:36 +0300