java - 在 Controller 的 @ResponseBody 中显示以字节形式返回的图像

标签 java spring-boot thymeleaf

在我的应用程序中,我有一个 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/

相关文章:

spring-boot - 使用 MyBatis Annotation Spring Boot 检索生成的 ID

spring-boot - Thymeleaf th :if…th:errors do not display error message in page after @PostMapping method checks for @Valid

页面上的 Spring MVC + Thymeleaf div 未生成

java - AWS Elastic Beanstalk 上的 Spring Boot/Tomcat 仅显示 404 页面

java - dom4j cdata(保留空格)

java - 通过封闭类类型变量绑定(bind)的内部类类型参数

java - 从 Oracle BPM 10g 打印到 Microsoft Document Image Writer 时禁止打印对话框

java - 当方法返回类型为 void 时,SpringBoot Controller 中的 CompletableFuture 不起作用

java - Thymeleaf:从 Java 代码访问外部字符串

java - 桌面应用程序中的 BIRT