java 从resource下载excel打不开

java 复制代码
    @GetMapping("/download/template")
    public void template(HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        InputStream inputStream = null;
        try {
    //从resource获取excel文件流
            inputStream = getClass().getClassLoader().getResourceAsStream("批量上传产品模板.xlsx");
            String fileName = "批量上传产品模板.xlsx";
            response.reset();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Length", String.valueOf(inputStream.available()));
            IoUtil.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("下载失败");
        } finally {
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        }
    }

由于Java项目在编译/Maven打包Excel等资源文件时,使用了Maven的filter,导致打包后的Excel文件乱码或者损坏。

需要再maven添加插件

XML 复制代码
<build>
   <plugins>
      <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-resources-plugin</artifactId>
         <configuration>
            <encoding>UTF-8</encoding>
            <nonFilteredFileExtensions>
               <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
               <nonFilteredFileExtension>xls</nonFilteredFileExtension>
            </nonFilteredFileExtensions>
         </configuration>
      </plugin>
   </plugins>
   <resources>
      <resource>
         <directory>src/main/resources</directory>
         <filtering>true</filtering>
      </resource>
   </resources>
</build>
相关推荐
土司大王2 小时前
LeetCode 79 单词搜索:Java 回溯模板、网格 DFS 与剪枝优化
java·算法·leetcode·深度优先
白远山2 小时前
智慧场馆解决方案小程序系统开发实战与架构设计指南
java·开发语言·小程序·架构
霸道流氓气质3 小时前
Spring AI Alibaba vs LangChain4j:Java AI 框架选型深度指南
java·人工智能·spring
敲代码的嘎仔3 小时前
从零实现视频续播 + 学习进度统计:前端心跳、条件更新、GROUP BY 统计全链路拆解
java·前端·数据库·学习·面试·职场和发展·音视频
一个有温度的技术博主3 小时前
深入理解 Spring Boot 自动装配
java·spring boot·后端
TT哇3 小时前
我把两个 Java 项目和一个 Python AI 服务部署到 2C2G:一次低成本 Docker 容器化实践
java·人工智能·python
星子yu3 小时前
【Java数据结构】二叉树 好像就这样?
java·数据结构
Irene19913 小时前
Flink 学习需要具备的 Java 基础知识总结
java·flink
宸津-代码粉碎机3 小时前
Spring AI企业级工程化落地手册|从Demo改造为生产级商用项目
java·人工智能·python·spring
Beyond_System|系统之外3 小时前
【学编程】Python基础编程题100道(1-20)
java·数据结构·算法