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>
相关推荐
隔壁小邓4 分钟前
在Java中实现优雅的CQRS架构
java·开发语言·架构
河边小咸鱼10 分钟前
pdd校招实习生内推【实时更新链接】2027届实习、2026届春招
java·c++·golang
zzb158014 分钟前
Agent学习-Reflection框架
java·人工智能·python·学习·ai
Holen&&Beer19 分钟前
Spring-Profile与部署说明
java·后端·spring
棉花糖超人19 分钟前
【操作系统】三、线程
java·开发语言·操作系统
liuyao_xianhui26 分钟前
优选算法_判断字符是否唯一_C++
java·开发语言·数据结构·c++·算法·链表
代码雕刻家29 分钟前
3.4.Maven-idea集成-导入Maven项目
java·maven·intellij-idea
2301_8035545234 分钟前
c++中的CAS是什么
java·开发语言·c++
java1234_小锋40 分钟前
Java高频面试题:RabbitMQ中有哪几种交换机类型?
java·rabbitmq·java-rabbitmq
翘着二郎腿的程序猿44 分钟前
SpringBoot集成@Slf4j注解:优雅输出日志,告别手动new Logger
java·spring boot·intellij-idea