【问题标题】:Spring boot - Grabbing a file from the file system in a Get RequestSpring boot - 在获取请求中从文件系统中获取文件
【发布时间】:2017-08-28 06:18:17
【问题描述】:

我正在尝试从文件系统中获取一个文件(在本例中为图像)并显示它。我可以从资源子目录中执行此操作,但是当我尝试转到文件系统时,它给了我一个 FileNotFound 异常。

java.io.FileNotFoundException: file:\Y:\Kevin\downloads\pic_mountain.jpg(文件名、目录名或卷标语法不正确)

我所有其余的代码都是从 Initialize.谢谢。

@RestController
public class ImageProducerController {

    @GetMapping("/get-text")
    public @ResponseBody String getText() {
        return "Hello World";
    }

    @GetMapping(value = "/get-jpg", produces = MediaType.IMAGE_JPEG_VALUE)
    public void getImage(HttpServletResponse response) throws IOException {

        FileSystemResource imgFile = new FileSystemResource("file:///Y:/Kevin/downloads/pic_mountain.jpg");
//        ClassPathResource imgFile = new ClassPathResource("images/pic_mountain.jpg");
        System.out.println(imgFile.getURL());
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        StreamUtils.copy(imgFile.getInputStream(), response.getOutputStream());
    }
}

【问题讨论】:

  • 为什么要这样访问文件系统??
  • 您确实意识到这段代码永远不会在您的 PC 之外运行,对吧?

标签: java spring spring-boot


【解决方案1】:

来自docs

public FileSystemResource(String path)
Create a new FileSystemResource from a file path

构造函数需要 url 的路径部分,所以在你的情况下只有 Y:/Kevin/downloads/pic_mountain.jpg

所以你应该尝试这样使用它:

FileSystemResource imgFile = new FileSystemResource("Y:/Kevin/downloads/pic_mountain.jpg");

顺便说一句。会不会是您错过了路径中的“用户”? -> Y:/Users/Kevin/downloads/pic_mountain.jpg

【讨论】:

  • 谢谢!那行得通。我看到的所有示例前面都有“文件:”部分。我现在可以停止用头撞墙了。
猜你喜欢
  • 2019-02-21
  • 2013-03-19
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多