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测试接口,文件编码正常,完美!

相关推荐
Nyarlathotep01134 小时前
SpringBoot Starter的用法以及原理
java·spring boot
dkbnull1 天前
深入理解Spring两大特性:IoC和AOP
spring boot
洋洋技术笔记1 天前
Spring Boot条件注解详解
java·spring boot
洋洋技术笔记2 天前
Spring Boot配置管理最佳实践
spring boot
用户8307196840823 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
大道至简Edward3 天前
Spring Boot 2.7 + JDK 8 升级到 Spring Boot 3.x + JDK 17 完整指南
spring boot·后端
洋洋技术笔记3 天前
Spring Boot启动流程解析
spring boot·后端
怒放吧德德4 天前
Spring Boot 实战:RSA+AES 接口全链路加解密(防篡改 / 防重放)
java·spring boot·后端
李慕婉学姐4 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
QQ5110082854 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php