FileSystemResource: how to set relative path

2019-08-22 07:33发布

问题:

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