首页 > 解决方案 > 使用 TypeORM 在 Postgres bytea 上保存缓冲区仅存储 10 个字节

问题描述

我试图在 postgres 数据库上保存一些图像,但只保存了 10 个字节的数据。

流程是这样的:

我在服务器上收到一个 base64 编码的字符串,然后将其加载到缓冲区,将其设置为我的实体并保存。但随后尝试从 db 恢复该信息,我只得到 10 个字节的数据,并在查询中使用 octet_length() 进行验证。

我的实体属性定义:

@Column({ "name": "entima_imagem", "type": "bytea", "nullable": false })
entima_imagem: Buffer;

我接收数据并保存的代码:

entity.entima_imagem = Buffer.from(base64String, "base64");
const repository = this.getRepositoryTarget(Entity);
const saved = await repository.save<any>(entity);

在服务器上,在保存之前,我正在将文件写入光盘,我可以毫无问题地对其进行可视化。

标签: node.jspostgresqltypescriptnestjstypeorm

解决方案


基于该评论https://github.com/typeorm/typeorm/issues/2878#issuecomment-432725569以及来自那里的 bytea 十六进制格式的想法https://www.postgresql.org/docs/9.0/datatype-binary。我做了以下事情:

将 Buffer 解码为十六进制字符串,使用 \x 对其进行转义,然后再次将其加载到 Buffer 中。

entity.entima_imagem = Buffer.from("\\x" + Buffer.from(base64String, "base64").toString("hex"));

现在数据保存没有问题,我可以按预期检索它们。

它看起来并不那么优雅,但现在解决了这个问题。


推荐阅读