首页 > 解决方案 > 在 Spring Boot 中使用 @ResponseBody 在浏览器上显示图像

问题描述

您好,我有这段代码可以在浏览器上显示保存在我的文件系统上的图像:

@GetMapping(value = "/prova/img/{id}", produces = MediaType.IMAGE_JPEG_VALUE)
public @ResponseBody byte[] getImageWithMediaType(@PathVariable String id) throws IOException {
    String path = uploadFolderPath +"/"+ id;
    if(Files.exists(Paths.get(path)) && !Files.isDirectory(Paths.get(path))) {
        InputStream in = getClass().getResourceAsStream(path);
        return IOUtils.toByteArray(in);
    }else {
        return null; //this is just for example it should never get here
    }

我收到此错误:

Cannot invoke "java.io.InputStream.read(byte[])" because "input" is null

有什么建议吗?

标签: javaspringspring-bootimage

解决方案


您的代码首先测试您的输入是否存在(作为 a File)并且不是目录,然后您继续尝试使用getClass().getResourceAsStream(path). 这通常不是你想要的。

试试吧InputStream in = new FileInputStream(path);

像这样:

if (Files.exists(Paths.get(path)) && !Files.isDirectory(Paths.get(path))) {
    InputStream in = new FileInputStream(path);
    return IOUtils.toByteArray(in);
}

PS:如果你使用的是 Java 9 或更高版本,则不需要IOUtils依赖项,只需使用readAllBytes. 由于您已经使用Filesand Path,我们可以像这样清理代码:

Path filePath = Paths.get(path);
if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
    InputStream in = Files.newInputStream(filePath, StandardOpenOption.READ);
    return in.readAllBytes();
}

推荐阅读