繁体   English   中英

在 spring 引导中使用 @ResponseBody 在浏览器上显示图像

[英]Showing an image on broswer using @ResponseBody in spring boot

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

@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

有什么建议吗?

您的代码首先测试您的输入是否存在(作为File )并且不是目录,然后是 go 并尝试使用getClass().getResourceAsStream(path)从 class 路径将其作为资源读取。 这通常不是你想要的。

试试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 由于您已经使用FilesPath ,我们可以像这样清理代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM