FileSystemResource:如何设置相对路径

问题描述 投票:0回答:2

我有这样的项目结构:

enter image description here

并跟随控制器:

@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()

但结果是一样的

java spring resources filesystems
2个回答
2
投票

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

-1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.