java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot获取resources静态资源

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

作者:何中应

本文主要介绍了SpringBoot获取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();
        }
    }

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

到此这篇关于SpringBoot获取resources目录下静态资源的两种方式的文章就介绍到这了,更多相关SpringBoot获取resources静态资源内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文