【问题标题】:Thymeleaf & Spring images generation from DB - will run into a strange behaviour从 DB 生成 Thymeleaf 和 Spring 图像 - 会遇到奇怪的行为
【发布时间】:2020-04-02 23:31:18
【问题描述】:

我正在做一个项目,我正在使用 Thymeleaf 和 Spring 创建网页,但我似乎无法正常生成图像。

我的数据库中有它们,所以它们生成得很好(到“生成”文件夹)。

因此,通过访问“项目”页面,图像应该在那里 - 但在我不切换 Intellij 并返回浏览器并再次单击刷新之前,它们不会显示在前端。我从未见过如此奇怪的行为。也许我在 Thymeleaf 中遗漏了一些东西?因为我是第一次使用它。

FILE_UPLOAD_ROOT - 从 application.properties 读取,它是 src/main/resources/generated/

然后我的控制器将一个项目列表传递给这个方法:

/**
 * Each entity that will extend {@link MediaModel} can use this method as a helper. In other words,
 * we should have these three fields added to the table that we're going to use:
 * pic(LONGBLOB), pic_name(VARCHAR), pic_type(VARCHAR)
 *
 * @param itemsList - database results for that we are going to generate images
 */
 public static void generateImages(Iterable<? extends MediaModel> itemsList) {

    itemsList.forEach(item -> {
        try {
            if (item.getPicName() == null) {
                return;
            } else {
                Files.write(Paths.get(FILE_UPLOAD_ROOT + item.getPicName() + "." + item.getPicType()), item.getPic());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}

在 Thymeleaf 我有: 我不太清楚为什么,但图片不是直接从 generated 文件夹中获取的,我应该只指定根目录,反正 Thymeleaf 根本无法显示它们。

&lt;img th:src="@{/{picName}.{picType}(picName=${project.picName},picType=${project.picType})}"/&gt;

保存项目图像的 MySQL 架构

create table projects
(
    id          bigint       not null
        primary key,
    created_at  datetime(6)  not null,
    updated_at  datetime(6)  not null,
    pic         longblob     null,
    pic_name    varchar(255) null,
    pic_type    varchar(255) null,
    category_id bigint       not null,
    constraint FKmagkis2tpqxxx8hq100rjo92v
        foreign key (category_id) references projects_categories (id)
            on delete cascade
);

当我尝试访问该页面时,直到我不会切换回 Intellij:

附注是的,我尝试将其部署到远程服务器,根本看不到它们,但我查看了目标文件夹,图像就在那里。

【问题讨论】:

    标签: mysql spring-boot thymeleaf


    【解决方案1】:

    为什么要将图像从数据库存储到压缩的 war 或 jar 内的文件夹中?这是不可取的

    要么在服务器上存储可部署的打包图像,然后从那里使用它。

    或

    只需使用下面的图像标签并即时渲染图像

    <img alt="img"  th:src="@{'data:image/jpeg;base64,'+${Base64EncodedImage}}" />
    

    P.S. - 在 IDE 中工作与在服务器上使用应用程序不同。您的方法将在 IDE 中有效,但在服务器上无效

    【讨论】:

    • 是的,我想出了这个,但无法让它们显示在 Thymeleaf 中,如何将图像映射到资源文件夹之外?尝试尽可能动态地做到这一点
    • 是不是想降低查询图片的数据库开销?那为什么没有免费的图片托管网址而不是将图片存储在数据库中。
    • 不,因为我必须重构太多才能使其以 Base64 方式工作
    • 也许你可以看看mkaroune.e-monsite.com/pages/spring/…。虽然我更喜欢使用Base64方法,因为它容易折射,而且它是防弹的解决方案。
    • 谢谢,我去看看
    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 2015-08-29
    • 2016-04-14
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    相关资源
    最近更新 更多