FileSystemResource:如何设置相对路径 [英] FileSystemResource: how to set relative path

查看:742
本文介绍了FileSystemResource:如何设置相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的项目结构:

和以下控制器:

@RestController
public class StubController {

    @GetMapping("/stub_mapping_template")
    public FileSystemResource getMappingTemplate() {
        return new FileSystemResource("/stub/mapping_template.csv");
    }
}

但是当我在浏览器中打开

but when I open in browser

localhost:8080/stub_mapping_template

什么都没有下载.

在调试中,我尝试输入:

in debug I tried to type:

new FileSystemResource("/stub/mapping_template.csv").exists()

并返回false.

我试图写:

new FileSystemResource("stub/mapping_template.csv").exists()

但结果相同

推荐答案

代替FileSystemResource使用ClassPathResource

 @GetMapping("/stub_mapping_template")
    public FileSystemResource getMappingTemplate(HttpServletResponse response) {
      ClassPathResource classPathResource = new ClassPathResource("/stub/mapping_template.csv");
      File file = classPathResource.getFile();

      InputStream in = new FileInputStream(file);

      response.setContentType(....);
      response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
      response.setHeader("Content-Length", String.valueOf(file.length()));
      FileCopyUtils.copy(in, response.getOutputStream());
      response.flushBuffer();
}

这篇关于FileSystemResource:如何设置相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆