SpringBoot通过接口下载resources下的文件方式
更新时间:2025年09月13日 16:45:56 作者:乘风御浪云帆之上
SpringBoot通过接口下载resources目录文件,解决jar包部署后资源路径不可直接访问的问题,利用Resource类加载文件,通过HttpServletResponse返回流,实现用户下载功能
解决的问题
当项目打成jar包进行部署时,一些示例文件放在resources目录下,提供接口供用户访问下载
文件存放位置

接口实现
@RequestMapping("/downloadExampleExcel")
@ResponseBody
public void downloadExampleExcel(HttpServletResponse response) {
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
Resource resource = new DefaultResourceLoader().getResource("classpath:example_add_infos.xls");
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + "example_add_infos.xls");
inputStream = resource.getInputStream();
servletOutputStream = response.getOutputStream();
IOUtils.copy(inputStream, servletOutputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
servletOutputStream = null;
}
if (inputStream != null) {
inputStream.close();
inputStream = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
IDEA 2020.1 搜索不到Chinese (Simplified) Language
小编在安装中文插件时遇到IDEA 2020.1 搜索不到Chinese ​(Simplified)​ Language Pack EAP,无法安装的问题,本文给大家分享我的解决方法,感兴趣的朋友一起看看吧2020-04-04
在Java中使用redisTemplate操作缓存的方法示例
这篇文章主要介绍了在Java中使用redisTemplate操作缓存的方法示例,在Redis中可以存储String、List、Set、Hash、Zset。感兴趣的可以了解一下2019-01-01
SpringBoot中@Conditional注解的介绍及实践
在 Spring Boot 中,@Conditional 注解用于实现 条件化 Bean 装配,本文将详细介绍 @Conditional 相关的注解,并结合实际应用示例讲解其使用方式,感兴趣的小伙伴可以了解下2025-03-03
java对象list使用stream根据某一个属性转换成map的3种方式举例
开发小伙伴们通常会需要使用到对象和Map互相转换的开发场景,下面这篇文章主要给大家介绍了关于java对象list使用stream根据某一个属性转换成map的3种方式,需要的朋友可以参考下2024-01-01


最新评论