获取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();}}
以上两种方式都能将后端静态资源返回给前端