SpringBoot中通过接口下载resources下的文件

SpringBoot中通过接口下载resources下的文件

解决的问题

  • 当项目打成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();
        }
    }
}
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
是的,SpringBoot可以提供接口让前端下载后端`resources`目录下的文件。可以通过以下步骤实现: 1. 在`application.properties`或`application.yml`配置`spring.resources.static-locations`属性,指定资源文件路径,例如: ``` spring.resources.static-locations=classpath:/static/,file:/path/to/resources/ ``` 这里配置了两个路径,一个是`classpath:/static/`,表示在`src/main/resources/static/`目录下查找静态资源;另一个是`file:/path/to/resources/`,表示在指定的`/path/to/resources/`目录下查找资源。 2. 创建一个Controller,用于处理下载请求,例如: ```java @RestController public class DownloadController { @GetMapping("/download") public ResponseEntity<Resource> downloadFile() throws IOException { Resource resource = new ClassPathResource("/static/test.txt"); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=test.txt"); return ResponseEntity.ok() .headers(headers) .contentLength(resource.contentLength()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(resource); } } ``` 这里假设要下载文件为`test.txt`,位于`src/main/resources/static/test.txt`。 3. 在前端页面添加下载链接,例如: ```html <a href="/download">Download</a> ``` 当用户点击该链接时,会向后端发送一个GET请求,后端会返回一个`test.txt`文件供用户下载。 注意:在实际开发,需要根据具体需求进行配置和实现。此处只是提供一个示例,具体实现方式可能会有所不同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乘风御浪云帆之上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值