Spring Boot 文件下载

1. 文件下载类

import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class DownloadUtil {

    public boolean fileDownload(HttpServletResponse response,String filePath,String fileName)
        throws UnsupportedEncodingException {
        
        File file = new File(filePath);//创建下载的目标文件,参数为文件的真实路径
        if(file.exists()){ //判断文件是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(fileName,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

2. 文件下载a标签

<a th:href="@{/download/} + ${fileName}+'?filePath='+${filePath}">点击下载文件</a>

filePath为文件的真实路径,由于路径的符号与RESTful API风格冲突,所以采取传统a标签的传参方式

3. 控制器

/**
     * 测试文件下载
     * @param fileName
     * @param filePath
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
@GetMapping("/download/{fileName}")
public String testDownload(@PathVariable("fileName") String fileName,String filePath,HttpServletResponse response) throws UnsupportedEncodingException {

    System.out.println("==>开始文件下载!");

    DownloadUtil downloadUtil = new DownloadUtil();

    downloadUtil.fileDownload(response,filePath,fileName);

    return null;
}

猜你喜欢

转载自www.cnblogs.com/lcsin/p/11705084.html