首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileSystemResource:如何设置相对路径

FileSystemResource:如何设置相对路径
EN

Stack Overflow用户
提问于 2017-12-25 17:22:15
回答 3查看 3.8K关注 0票数 0

我的项目结构是这样的:

和下面的控制器:

代码语言:javascript
复制
@RestController
public class StubController {

    @GetMapping("/stub_mapping_template")
    public FileSystemResource getMappingTemplate() {
        return new FileSystemResource("/stub/mapping_template.csv");
    }
}

但当我在浏览器中打开时

代码语言:javascript
复制
localhost:8080/stub_mapping_template

不下载任何内容。

在debug中,我尝试键入:

代码语言:javascript
复制
new FileSystemResource("/stub/mapping_template.csv").exists()

它返回false

我试着写下:

代码语言:javascript
复制
new FileSystemResource("stub/mapping_template.csv").exists()

但结果是一样的

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-12-25 17:27:42

使用ClassPathResource代替FileSystemResource

代码语言:javascript
复制
 @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();
}
票数 3
EN

Stack Overflow用户

发布于 2020-09-02 02:08:03

或者,如果你想继续使用FileSystemResource,你可以这样做:

代码语言:javascript
复制
 new FileSystemResource("src/main/resources/stub/mapping_template.csv");
票数 0
EN

Stack Overflow用户

发布于 2017-12-25 17:37:10

也许FileSystemResource会获取你的文件的完整url。其中一种方法是,将路径从pc上的“我的电脑”复制。并从url的开头继续删除。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47967331

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档