FileSystemResource: how to set relative path

耗尽温柔 提交于 2020-01-06 07:18:24

问题


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.

I tried to write:

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

but result the same


回答1:


Instead of FileSystemResource use 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();
}



回答2:


Perhapsly FileSystemResource takes full url of your file. One of the technique is, you copy the path from "My Computer" on your pc. And keep deleting from start of the url



来源:https://stackoverflow.com/questions/47967331/filesystemresource-how-to-set-relative-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!