java - 在 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
有什么建议吗?
解决方案
您的代码首先测试您的输入是否存在(作为 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
. 由于您已经使用Files
and Path
,我们可以像这样清理代码:
Path filePath = Paths.get(path);
if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
InputStream in = Files.newInputStream(filePath, StandardOpenOption.READ);
return in.readAllBytes();
}
推荐阅读
- c# - 使用跨越所有显示器的 C# 绘制线
- javascript - 使用 OR 对多对多搜索进行续集
- android - 将布局放置在 FrameLayout 根中或将布局作为根而不使用 FrameLayout 有什么区别?
- javascript - 在javascript中按属性选择元素,其中属性名称有冒号?
- java - 有没有办法遍历 2 个 for 循环,使得 (i+j) > 3
- python - 用 python 和 IPython 小部件表示无穷大
- r - R data.table 函数根据同一行上的引用列号复制值
- runtime-error - pytorch:RuntimeError:具有多个值的张量的布尔值不明确
- oracle - Debezium CDC 连接器说 java.library.path 中没有 ocijdbc11
- pypy - 如何解决或报告 pathos 和 pypy 之间的不兼容问题