场景

在页面中点击模板,实现excel模板的下载。

效果

SpringBoot+thymeleaf实现文件下载(已实践,全流程)SpringBoot+thymeleaf实现文件下载(已实践,全流程)

实现

thymeleaf页面代码

<button id="dowloadBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> 模板下载</button>

在当前页面引入js文件

<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
     th:replace="layout/layout(title='数据',cssPaths='/public/css/plugins/jsTree/style.min.css',jsPaths='/modular/receiveOrder/wmsReceiveOrder.js')">

js中

//模板下载按钮点击事件
    $("#dowloadBtn").click(function () {
        templateDowload()
    });

在实现方法中

//EXCel模板下载
function templateDowload(){
    window.location.href="/wmsReceiveOrder/downloadOnlineLearnMaterials";
}

请求到后台Controller

 @Description("模板下载")
    @RequestMapping("/downloadOnlineLearnMaterials")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "template.xlsx";// 设置文件名,根据业务需要替换成要下载的文件名
        if (fileName != null) {
            //设置文件路径
            String realPath = configProperties.getExcelTemplateDpwloadPath();//这里使用配置类配置文件路径
            File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

 

其中String realPath = configProperties.getExcelTemplateDpwloadPath();

是使用的配置类配置文件路径,这里可以根据具体业务修改,可以改为固定路径。

具体怎样使用配置文件以及配置类实现文件上传下载路径的修改

参照:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/88786320

比如这里的模板文件,路径为

SpringBoot+thymeleaf实现文件下载(已实践,全流程)SpringBoot+thymeleaf实现文件下载(已实践,全流程)

相关文章: