Spring Boot basic study notes 15: realize file download function

Zero, learning goals

  1. Master the use of Spring Boot to realize the file download function

1. Overview of file download

Downloading files can be achieved through IO streams, so most frameworks do not encapsulate file downloads. When the file is downloaded, the analysis and processing of different browsers are involved, and Chinese garbled characters may appear. Therefore, it is necessary to try to solve the Chinese garbled problem.

Second, realize the file download function

(1) Create a Spring Boot project

  • Create FileDownloadDemo project, add Web and Thymeleaf dependencies
    Insert picture description here
    Insert picture description here
    Insert picture description here
    Insert picture description here
  • A tool class that introduces file download in pom.xml depends on commons-io
    Insert picture description here
<dependency>                             
    <groupId>commons-io</groupId>        
    <artifactId>commons-io</artifactId>  
    <version>2.6</version>               
</dependency>                            

(2) Integrate Bootstrap

  • Copy bootstrap-4.0.0 in the resources/static of the project FileUploadDemo of the 14th lecture to the corresponding location of the current project
    Insert picture description here
    Insert picture description here

(3) Prepare files to be downloaded

  • Create a download directory on the D drive to store the files to be downloaded
    Insert picture description here
  • One is the plain English file name, the other is the Chinese and English file name

(4) Compile a file download page

  • Create a file download page in the templates directory-filedownload.html
    Insert picture description here
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,shrink-to-fit=no">
    <link th:href="@{/bootstrap-4.0.0/css/bootstrap}" rel="stylesheet">
    <script th:src="@{/bootstrap-4.0.0/js/jquery-3.4.1.js}"></script>
    <script th:src="@{/bootstrap-4.0.0/js/bootstrap.bundle.js}"></script>
    <script th:src="@{/bootstrap-4.0.0/js/bootstrap.js}"></script>
    <title>文件下载</title>
</head>
<body>
<div class="w-50 m-auto bg-info">
    <h3 class="h3">文件下载</h3>
    <label>Spring Boot.txt</label>
    <a th:href="@{/downloadFile(filename='Spring Boot.txt')}">下载</a><br/>
    <label>Spring Boot开发基础.txt</label>
    <a th:href="@{/downloadFile(filename='Spring Boot开发基础.txt')}">下载</a>
</div>
</body>
</html>

(5) Write file download controller

Insert picture description here

package net.hw.lesson15.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

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

/**
 * 功能:文件下载控制器
 * 作者:华卫
 * 日期:2021年03月01日
 */
@Controller
public class FileDownloadController {
    
    
    @RequestMapping("/toFileDownload")
    public String toDownload(HttpServletRequest request) {
    
    
        return "filedownload";
    }

    @RequestMapping("/downloadFile")
    public ResponseEntity<byte[]> downloadFile(String filename) {
    
    
        // 定义下载文件所在的位置
        String dir="D:/download";
        File file = new File(dir + File.separator + filename);
        // 设置响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        // 让浏览器以附件,即下载的方式打开
        httpHeaders.setContentDispositionFormData("attachment", filename);
        // 定义以流的形式返回数据
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
    
    
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            // 重新实例化headers,否则前台不会显示出错信息
            httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(e.getMessage().getBytes(), httpHeaders, HttpStatus.EXPECTATION_FAILED);
        }
    }
}

(6) Start the application and test the effect

  • accesshttp://localhost:8080/toFileDownload
    Insert picture description here
  • View the downloaded file
    Insert picture description here
  • As you can see, if you download a file with a pure English file name, everything is normal, but the file name contains Chinese, and the downloaded file name will have garbled characters.
  • Delete Spring Boot.txt in the download directory, download the file again, check the result, the page displays an error message
    Insert picture description here

3. Solve the problem of garbled Chinese name files

(1) Write the method to obtain the file name in the file download controller

Insert picture description here

(2) Modify the downloadFile method in the file download controller

Insert picture description here

(3) Start the application and test the effect

Insert picture description here
Insert picture description here

  • As you can see, there will be no garbled characters when downloading Chinese file names.

Four, after-class development exercises

  • Modify the code, download other types of files and test.

Guess you like

Origin blog.csdn.net/howard2005/article/details/114254546