Spring boot - 在Get Request中从文件系统中获取文件

时间:2017-08-27 18:57:03

标签: java spring spring-boot

我正在尝试从文件系统中获取文件(在本例中为图像)并显示它。我可以从resources子目录中做到这一点就好了,但是当我尝试转到文件系统时它会给我一个FileNotFound异常。

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

我的所有其余代码都是从Initialize生成的vanilla spring boot。谢谢。

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

1 个答案:

答案 0 :(得分:2)

来自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