使用TypeORM在Postgres bytea上保存缓冲区只存储10个字节

问题描述 投票:0回答:2

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

流程是这样的:

我在服务器上收到base64编码的字符串,然后我将其加载到Buffer,将其设置为我的实体并保存。但是然后尝试从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.js postgresql typescript nestjs typeorm
2个回答
0
投票

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

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

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

现在数据保存没有问题,我可以像它应该的那样检索它们。

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


0
投票

我有类似的问题。看起来typeorm有0x00字节的问题。它从前0字节开始切片。

类似的解决方法对我有用:

@Column({ type: "bytea", nullable: false })
public file: Buffer;

保存时:

log.file = ("\\x" + file.toString( "hex" )) as any;

从@JDuwe建议的“\\ x”+内容字符串创建缓冲区对我来说不起作用。我必须为typeorm提供一个字符串,而不是Buffer。

© www.soinside.com 2019 - 2024. All rights reserved.