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

相关推荐
用户3521802454752 小时前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
昵称为空C5 小时前
手撸一个动态 SQL 执行引擎:不重启服务,在线增删改查任意数据库
spring boot·后端
霸道流氓气质1 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
于先生吖1 天前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端
Flittly1 天前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
星落zx1 天前
Spring Boot 多模型集成:优雅调用全球主流大模型
人工智能·spring boot·chatgpt
一杯奶茶¥1 天前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目
进阶的小名1 天前
Spring Boot SSE + Nginx 配置:解决 EventSource 不实时返回、连接超时、流式响应被缓冲问题
spring boot·后端·nginx
我登哥MVP1 天前
SpringCloud Alibaba 核心组件解析:服务链路追踪
java·spring boot·后端·spring·spring cloud·java-ee·maven