Spring Boot 下载文件(word/excel等)文件名中文乱码问题|构建打包不存在模版文件(templates等)

Spring Boot 下载文件(word/excel等)文件名中文乱码问题|构建打包不存在模版文件(templates等)

准备文件,这里我放在resource下的templates路径

在pom中配置构建打包的资源,更新maven

如果使用了assembly打包插件这样配置可能仍不生效,检查并配置 package.xml文件

编写下载接口,返回要下载的模版文件,fileName可以根据需要灵活配置

java 复制代码
    @GetMapping("/download")
    @ApiOperation(value = "下载导入模版", notes = "")
    public void download(HttpServletResponse response) throws IOException {
        String fileName = "数据项集导入模板.xlsx";
        //获得待下载文件的绝对路径
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "templates";
        //获取文件输入流
        FileInputStream fileInputStream = new FileInputStream(new File(realPath, fileName));
        //文件名包含中文时需要进行中文编码,否则会出现乱码问题
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        ServletOutputStream servletOutputStream = response.getOutputStream();
        int len = 0;
        //设置一个缓冲区,大小取决于文件内容的大小
        byte[] buffer = new byte[1024];
        //每次读入缓冲区的数据,直到缓冲区无数据
        while ((len = fileInputStream.read(buffer)) != -1) {
            //输出缓冲区的数据
            servletOutputStream.write(buffer, 0, len);
        }
        servletOutputStream.close();
        fileInputStream.close();
    }

这样做完后,使用swagger测试接口大概率会出现"%A8%A1%E6%9D%BF.xlsx"这种格式,这是由于Swagger对文件名进行了URL编码,导致文件名在下载时显示为编码后的形式。

直接使用浏览器进行Get测试接口,文件编码正常,完美!

相关推荐
IT毕设实战小研39 分钟前
Java毕业设计选题推荐 |基于SpringBoot的健身爱好线上互动与打卡社交平台系统 互动打卡小程序系统
java·开发语言·vue.js·spring boot·vue·毕业设计·课程设计
BillKu6 小时前
Spring Boot 3中JWT密钥安全存储方案
spring boot·后端·安全
IT毕设实战小研13 小时前
基于SpringBoot的救援物资管理系统 受灾应急物资管理系统 物资管理小程序
java·开发语言·vue.js·spring boot·小程序·毕业设计·课程设计
Warren9814 小时前
MySQL,Redis重点面试题
java·数据库·spring boot·redis·mysql·spring·蓝桥杯
自由自在的小Bird17 小时前
kafka初步介绍
spring boot·后端·kafka
MrSYJ18 小时前
为什么引入springsecurity的依赖后,会自动创建了过滤器链
spring boot·后端·代码规范
Q_Q196328847521 小时前
python基于Hadoop的超市数据分析系统
开发语言·hadoop·spring boot·python·django·flask·node.js
小乌龟不会飞21 小时前
【SpringBoot】统一功能处理
java·spring boot·后端
考虑考虑21 小时前
JPA中的EntityGraph
spring boot·后端·spring