gstackoverflow
gstackoverflow

Reputation: 37034

FileSystemResource: how to set relative path

I have project structure like this:

enter image description here

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

Upvotes: 0

Views: 13586

Answers (3)

Tracy Xia
Tracy Xia

Reputation: 390

Or if you want to stick with FileSystemResource, you could do this:

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

Upvotes: 0

pvpkiran
pvpkiran

Reputation: 27038

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

Upvotes: 6

Sourav
Sourav

Reputation: 155

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

Upvotes: -1

Related Questions