SpringBoot获取resources下的文件

本文介绍了如何使用Spring MVC API实现通过HttpServletRequest和HttpServletResponse下载资源文件,具体展示了ExcelUtils类中exportLocalExcel方法,用于导出指定路径的template.xlsx文件为Excel。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例如下载/resources/excel/template.xlsx

    @GetMapping("/download")
    public void downloadFile(HttpServletRequest request,
                             HttpServletResponse response) {
        String fullFileName = "excel/template.xlsx";
        ExcelUtils.exportLocalExcel(request, response, fullFileName);
    }

ExcelUtils.java

public class ExcelUtils {

    /**
     * 导出本地Excel
     *
     * @param httpRequest  请求信息
     * @param httpResponse 响应信息
     * @param pathFileName 带路径的文件名字
     */
    public static void exportLocalExcel(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String pathFileName) throws Exception {
        String[] split = pathFileName.split("/");
        ClassPathResource classPathResource = new ClassPathResource(pathFileName);
        InputStream fis = classPathResource.getInputStream();
        httpResponse.setContentType("application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String rawFileName = split[split.length - 1];
        String fileName = FileNameUtil.getPrefix(rawFileName);
        String suffix = FileNameUtil.getSuffix(rawFileName);
        httpResponse.setHeader("Content-Disposition", "attachment;filename=" + getFileName(fileName, httpRequest) + "." + suffix);
        ServletOutputStream outputStream = httpResponse.getOutputStream();
        if (fis.available() != 0) {
            httpResponse.setStatus(200);
        }
        IOUtils.copy(fis, outputStream);
        fis.close();
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 处理文件名字编码
     *
     * @param fileName 文件名字
     * @param request  请求信息
     * @return 编码后文件名
     * @throws Exception 异常信息
     */
    private static String getFileName(String fileName, HttpServletRequest request) throws Exception {
        String ua = request.getHeader("User-Agent").toLowerCase();
        if (ua.contains("macintosh") && !ua.contains("chrome")) {
            //浏览器: safari
            return new String(fileName.getBytes(), "ISO8859-1");
        }
        //默认utf-8
        return URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
    }
}
### 如何在Spring Boot中读取resources目录下的文件 在Spring Boot应用程序中,`resources` 文件夹是一个特殊的位置,通常用于存储配置文件、静态资源和其他运行时所需的文件。要从 `resources` 文件夹中读取文件,可以使用多种方法。 #### 使用 ClassLoader 的 getResourceAsStream 方法 一种常见的方法是通过 Java 的 `ClassLoader` 类来获取文件流。此方式适用于大多数场景,尤其是当目标文件位于类路径下时。下面展示了一个简单的例子: ```java import java.io.InputStream; import org.springframework.core.io.ClassPathResource; public class FileReaderExample { public static void readFileFromResources() throws Exception { InputStream inputStream = new ClassPathResource("example.txt").getInputStream(); try (var reader = new java.util.Scanner(inputStream)) { while(reader.hasNextLine()) { System.out.println(reader.nextLine()); } } catch(Exception e){ throw new RuntimeException("Failed to read file", e); } } } ``` 上述代码片段展示了如何利用 `ClassPathResource` 来加载名为 `example.txt` 的文件[^3]。注意,这里的文件名应相对于 `src/main/resources` 路径指定。 另一种替代方案涉及直接调用 `Thread.currentThread().getContextClassLoader().getResourceAsStream()` 函数实现相同功能: ```java InputStream inputStream = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("example.txt"); if(inputStream == null){ throw new IllegalArgumentException("File not found!"); } // 继续处理输入流... ``` 这两种技术都可以有效地访问嵌套于 JAR 或 WAR 包内部的资源文件,在开发阶段以及部署后的生产环境中均适用。 #### 配置与注意事项 如果发现尝试读取特定文件失败(即返回null),可能是因为该文件未正确定位到classpath根目录或者拼写错误等原因造成的。确认所请求的相对路径无误非常重要。 另外需要注意的是,对于大型二进制数据或其他不适合一次性载入内存的数据对象,则需考虑采用分块传输等方式优化性能表现;而对于纯文本型的小规模文档来说,上面提到的方法已经足够满足需求了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值