node.js - 使用 TypeORM 在 Postgres bytea 上保存缓冲区仅存储 10 个字节

标签 node.js postgresql typescript nestjs typeorm

我正在尝试在 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/

相关文章:

node.js - 使用 typescript 时nodemon不刷新

node.js - 如何在没有用户和登录的情况下使用 JWT?

node.js - 如何在 Docker 中为 Postgres 运行 sql 脚本?

sql - 连接和排序 1 :n relationship 中两个表的不同行

postgresql - Go 插入时偶尔出现 PostgreSQL "Duplicate key value violates unique constraint"错误

data-binding - 在 Angular 2 中加载第一页时设置 [(ngModel)] 的值

javascript - 如何使用 javascript 按数组分组并确定总行数

javascript - NodeJS 条件决策

javascript - 如何在 Nodejs 中使用 Promises 进行同步 http 调用

mysql - 德鲁巴 : How can I know if the db is mysql or postgres