当前位置: 首页 > news >正文

获取resources目录下静态资源的两种方式

说明:本文介绍在 Spring Boot 项目中,获取项目下静态资源的两种方式。

场景

一般来说,项目相关的静态资源,都会放在当前模块的 resources 目录下,如下:

在这里插入图片描述

方式一:返回字节数组

可以通过下面这种方式,读取文件(注意文件路径,从 resources 开始),返回给前端文件的字节数组

    @GetMapping("/get-template-1")public byte[] getTemplate() throws IOException {// 1.获取文件ClassPathResource resource = new ClassPathResource("template/excel/full/学生信息模板-填充.xlsx");// 2.构建响应头String fileName = "学生信息模板.xlsx";String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentDispositionFormData("attachment", encodedFileName);// 3.返回return ResponseEntity.ok().headers(headers).body(resource.getInputStream().readAllBytes()).getBody();}

这种方式,需要编译环境是 Java 10(包括10) 以上的,不然编译不通过

在这里插入图片描述

在 pom 文件末尾定义编译环境(大于或等于10)

    <build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>17</source><target>17</target></configuration></plugin></plugins></build>

方式二:写入到响应中

也可以用下面这种方式,将文件流写入到响应对象中

    @GetMapping("/get-template-2")public void getTemplate2(HttpServletResponse response) throws IOException {// 1.获取文件ClassPathResource resource = new ClassPathResource("template/excel/full/学生信息模板-填充.xlsx");// 2.构建响应头String fileName = "学生信息模板.xlsx";String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);// 3.写入到响应对象中try (InputStream inputStream = resource.getInputStream();OutputStream outputStream = response.getOutputStream()) {inputStream.transferTo(outputStream);outputStream.flush();}}

以上两种方式都能将后端静态资源返回给前端

在这里插入图片描述

http://www.dtcms.com/a/507631.html

相关文章:

  • 一个域名可以做几个网站吗最好加盟网站建设
  • Android 自定义 View 如何设置默认尺寸
  • C#技术栈
  • 广东建设监理网站如何查企业的工商信息
  • INT301 Bio-computation 生物计算(神经网络)Pt.2 监督学习模型:感知器(Perceptron)
  • 机器学习(4)多特征与向量化
  • stripe/paypal
  • 机器学习(5)特征缩放与梯度下降收敛
  • 英飞凌推出首款100V aec合格GaN晶体管
  • 李宏毅机器学习笔记27
  • 机器学习作业七
  • openEuler安装jdk,nginx,redis
  • ffmpeg 交叉编译
  • Python编程之面向对象
  • 建设一个网站大概费用门户网站开发工具
  • OpenCV cv::Mat.type() 以及类型数据转换
  • Elasticsearch批量写入50万数据
  • 爬取GitHub开源项目信息并生成词云:从数据抓取到可视化实践
  • 做阀门的网站域名有了怎么建设网站
  • 西安交大Nat. Commun:749.276 cm²认证效率19.50%,通过IEC测试迈向产线
  • 百度站长平台登录网站图片自动轮换怎么做的
  • KuiklyUI 科普:UI 如何映射到 Android View 并完成渲染
  • 【2025-系统规划与管理师】第11章:信息系统治理
  • Python中如何实现数据库迁移
  • 第6部分:使用Netty的常见坑与注意事项
  • 广东企业品牌网站建设价格免费做网站的方法
  • 家政小程序系统开发:打造便捷高效的家政服务平台
  • CVE-2025-57833研究分析
  • 基于西门子proneta软件的网络设备台账自动管理软件
  • 深入大模型-12-Python虚拟环境的管理venv和uv和conda