我正在尝试在 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);
在服务器上,在保存之前,我正在将文件写入光盘,我可以毫无问题地对其进行可视化。
最佳答案
基于该评论 https://github.com/typeorm/typeorm/issues/2878#issuecomment-432725569以及来自那里的 bytea 十六进制格式的想法 https://www.postgresql.org/docs/9.0/datatype-binary.html我做了以下事情:
将 Buffer 解码为十六进制字符串,用\x 对其进行转义,然后再次将其加载到 Buffer 中。
entity.entima_imagem = Buffer.from("\\x" + Buffer.from(base64String, "base64").toString("hex"));
现在数据保存没有问题,我可以像它应该的那样检索它们。
它看起来并不那么优雅,但暂时解决了这个问题。
关于node.js - 使用 TypeORM 在 Postgres bytea 上保存缓冲区仅存储 10 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55498140/