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>
相关推荐
未若君雅裁29 分钟前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
阿维的博客日记1 小时前
Nacos 为什么能让配置动态生效?(涉及 @RefreshScope 注解)
java·spring
雨辰AI1 小时前
SpringBoot3 + 人大金仓读写分离 + 分库分表 + 集群高可用 全栈实战
java·数据库·mysql·政务
辰海Coding3 小时前
MiniSpring框架学习-完成的 IoC 容器
java·spring boot·学习·架构
小小编程路3 小时前
C++ 多线程与并发
java·jvm·c++
AI视觉网奇3 小时前
linux 检索库 判断库是否支持
java·linux·服务器
时空自由民.3 小时前
vim入门配置教程
编辑器·vim·excel
她的男孩3 小时前
从零搭一个企业后台,为什么我把能力拆成 Starter 和 Plugin
java·后端·架构
RainCity3 小时前
Java Swing 自定义组件库分享(七)
java·笔记·后端