简体   繁体   English

FileSystemResource:如何设置相对路径

[英]FileSystemResource: how to set relative path

I have project structure like this:我有这样的项目结构:

在此处输入图片说明

and following controller:和以下控制器:

@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

nothing downloads.没有什么下载。

in debug I tried to type:在调试中,我尝试输入:

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

and it returns false .它返回false

I tried to write:我试着写:

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

but result the same但结果一样

Instead of FileSystemResource use ClassPathResource使用ClassPathResource代替FileSystemResource

 @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,你可以这样做:

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

Perhapsly FileSystemResource takes full url of your file.也许 FileSystemResource 需要您文件的完整 url。 One of the technique is, you copy the path from "My Computer" on your pc.其中一种技术是,您将路径从“我的电脑”复制到您的 PC 上。 And keep deleting from start of the url并继续从网址的开头删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM