在我的应用程序中,我有一个 Controller ,当表单传递图片时,它将图片存储在所需的目录中。图片的名称就是userId。我正在使用 Spring-boot 和 Thyemeleaf。 将图像存储在具有 userId 的目录中的函数工作正常。 现在我有一个函数可以获取此图像并将其作为字节返回,以便我从 Thymeleaf 访问它。
@RequestMapping(value = "/displayPicture/{userId}")
@ResponseBody
public byte[] getImage(@PathVariable(value = "userId") String userId) throws IOException {
File serverFile = new File("path");
return Files.readAllBytes(serverFile.toPath());
}
如何实现这一目标?
我之前从不同的 Controller 返回 userId,如下所示:
modelAndView.addObject("userId", user.getUserId());
html 表单:
<form method="POST" th:action="@{/form}"
enctype="multipart/form-data" role="form">
<input id="fileUpload" type="file" name="file" onchange="this.form.submit()"/>
<img th:href="/displayPicture/${userId}"/> // This is what I am asking how to do correctly
</form>
我希望当图片上传时,当modelAndView返回时,它返回并显示上传的图片。 预先感谢您。
最佳答案
上下文相关的 URL?
<img th:href="@{/displayPicture/{userId}(userId=${userId})}"/>
关于java - 在 Controller 的 @ResponseBody 中显示以字节形式返回的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46093796/