FileSystemResource:如何设置相对路径
FileSystemResource: how to set relative path
我有这样的项目结构:
和以下控制器:
@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()
它 returns false
.
我试着写:
new FileSystemResource("stub/mapping_template.csv").exists()
但结果相同
而不是 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();
}
也许 FileSystemResource 占用了您文件的全部 url。其中一项技术是,您从 "My Computer" 复制路径到您的电脑上。并从 url
开始继续删除
或者如果您想坚持使用 FileSystemResource,您可以这样做:
new FileSystemResource("src/main/resources/stub/mapping_template.csv");
我有这样的项目结构:
和以下控制器:
@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()
它 returns false
.
我试着写:
new FileSystemResource("stub/mapping_template.csv").exists()
但结果相同
而不是 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();
}
也许 FileSystemResource 占用了您文件的全部 url。其中一项技术是,您从 "My Computer" 复制路径到您的电脑上。并从 url
开始继续删除或者如果您想坚持使用 FileSystemResource,您可以这样做:
new FileSystemResource("src/main/resources/stub/mapping_template.csv");