如何在Spring中显示数据库中的图片?

How to display a picture from a database in Spring?

我知道这是一个愚蠢的问题,您可以在 Internet 上找到如何执行此操作的示例,但基本上我发现了一些太混乱的代码,我什么都不懂... 我在本地主机上有一个博客数据库,我在那里成功上传了 post(名称、日期、文本和图片)的所有信息。但我通常不知道如何从那里显示它。也许有人不会太懒,至少展示一部分代码或想法本身......这里我有一个控制器,我将信息加载到数据库中

@PostMapping("addArticle")
public String postAddArticle(@AuthenticationPrincipal User user, Date timeArticle, @RequestParam String title, String author,
                             @RequestParam String anons, @RequestParam String text,
                             @RequestParam("file") MultipartFile file, Model model) {
    Byte[] bArray = null;

    author = user.getUsername();

    Calendar calendar = Calendar.getInstance();
    timeArticle = calendar.getTime();

    try {
        bArray = new Byte[file.getBytes().length];
        int i = 0;
        for(byte b : file.getBytes()){
            bArray[i++] = b;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Post post = new Post(title,timeArticle, author, anons, text, bArray );
    post.setTitle(title);
    post.setTimeArticle(timeArticle);
    post.setAuthor(author);
    post.setAnons(anons);
    post.setText(text);
    post.setImage(bArray);
    postRepository.save(post);

    return "redirect:/adminPage";
}

代码有效,所有内容都已成功添加到数据库中,包括图像。现在告诉我如何在 img 标签中使用 thymeleaf 显示它?

在 Web 应用程序中,通常您会将图像添加到资源文件夹,然后可以通过应用程序访问这些图像,如果适合您,请参考: images as static resources。所以一旦这个应用程序在部署后被打包和提取,图像路径将被解析并且可以在浏览器上看到。

如果你想将图像存储在数据库中,你可以尝试将它们保存为数据库中的 base64 编码字符串,为此你可以使用这个: base64 conversion