spring-mvc - 使用 thymeleaf 和 spring boot 上传和显示图像

标签 spring-mvc file-upload spring-boot thymeleaf

这是我在 Spring Boot 中上传图片的代码:

String root = ctx.getRealPath("/");
File dir = new File(root + File.separatorChar + "images");
if (!dir.exists())
    dir.mkdir();

String path = dir.getAbsolutePath() + File.separatorChar
            + product.getProductName() + "."
            + file.getContentType().split("/")[1];
System.out.println(path);
File file1 = new File(path);
try {
    FileOutputStream fod = new FileOutputStream(file1);
    fod.write(file.getBytes());
    fod.close();
    product.setProductPicture("/images/" + product.getProductName()
            + "." + file.getContentType().split("/")[1]);
} catch (IOException e) {
    e.printStackTrace();
}

文件上传工作正常,此代码的唯一问题是当我使用 ctx.getRealPath("/") 时它返回临时位置,当我重新启动 Spring Boot 应用程序时,我会丢失已经上传的现有文件,因为它会创建一个新的临时目录。

这会导致一些问题,因为我还必须在我的网站上显示这些图片,现在它返回“找不到图像错误”。

所以我需要一个解决方案,它允许我在一个永久位置上传文件并从那里在浏览器上提供文件。

注:我正在使用 thymeleaf 进行查看。

最佳答案

我找到了解决我的问题的方法。我创建了一个新函数,它只会返回 bytes[]并作为响应正文发送,如下所示:

@RequestMapping(value = "image/{imageName}")
@ResponseBody
public byte[] getImage(@PathVariable(value = "imageName") String imageName) throws IOException {

    File serverFile = new File("/home/user/uploads/" + imageName + ".jpg");

    return Files.readAllBytes(serverFile.toPath());
}

并在 html <img alt="Image" th:src="@{image/userprofile}" width="250" height="250"/>

关于spring-mvc - 使用 thymeleaf 和 spring boot 上传和显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41083751/

相关文章:

spring-boot - 如何在多个 Spring Boot 应用程序之间共享 JPA 实体

java - 启动springboot时出现logback错误

java - Spring MVC。渲染布局

php - Laravel 验证文件数组总允许上传大小

java - Spring Boot结构体中应用Yml Map<String,Map<String,List<Object>>>

file-upload - 使用 youtube 的 api 上传到 youtube 时显示进度条

java - selenium 如何测试它是否具有对文件的读取访问权限

java - 使请求参数绑定(bind)不区分大小写

spring - 在 SecurityContext 中找不到 Authentication 对象 - Spring 3.2.2

java - 注入(inject) Autowiring 的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException :