【问题标题】:FileSystemResource: how to set relative pathFileSystemResource:如何设置相对路径
【发布时间】:2017-12-25 09:22:14
【问题描述】:

我有这样的项目结构:

和以下控制器:

@RestController
public class StubController {

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

但是当我在浏览器中打开时

localhost:8080/stub_mapping_template

没有下载。

在调试中我尝试输入:

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

它返回false

我试着写:

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

但结果相同

【问题讨论】:

  • 你好,在一个sevlet中,你需要使用getServletContext()来找到你的项目的根,例如:Paths.get(getServletContext().getRealPath("web-inf/myfile");
  • 不是文件系统资源。在运行时,mapping_template.csv 不在文件系统上。它在您部署的 jar 文件中,可由类加载器加载。

标签: java spring resources filesystems


【解决方案1】:

而不是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();
}

【讨论】:

  • 它正在工作,但浏览器呈现我的 csv 文件而不是下载它。我怎样才能下载这个文件?
  • 下载你需要返回一个流作为响应(HttpServletResponse)
  • 你能修改我的例子吗?
【解决方案2】:

或者如果你想坚持使用 FileSystemResource,你可以这样做:

 new FileSystemResource("src/main/resources/stub/mapping_template.csv");

【讨论】:

    【解决方案3】:

    也许 FileSystemResource 获取文件的完整 url。其中一项技术是,您从电脑上的“我的电脑”复制路径。并从 url 的开头继续删除

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 2021-06-17
      相关资源
      最近更新 更多