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



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

流程如下所示:

我在服务器上收到一个 base64 编码的字符串,然后将其加载到 Buffer,将其设置为我的实体并保存。但是后来尝试从数据库恢复该信息,我只得到了 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 hex格式的想法 https://www.postgresql.org/docs/9.0/datatype-binary.html 我做了以下工作:

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

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

现在数据已毫无问题地保存,我可以按预期检索它们。

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

我有类似的问题。看起来typeorm的字节有问题0x00。它从前 0 个字节开始对所有内容进行切片。

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

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

保存时:

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

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

也许自从上次回答 postgres 或 typeorm 解决了它,但在两者的最新版本上,我设法在没有任何"黑客"的情况下完成了这项工作这是实体列的代码

@Column({
    name: 'imageData',
    type: 'bytea',
    nullable: false,
})
imageData: Buffer;

我唯一做的是将 base64 字符串转换为缓冲区,但这与 typeorm 无关

 constructor(imageDataBase64: string) {
    if (imageDataBase64) {
        this.imageData = Buffer.from(imageDataBase64, 'base64');
    }
}

即使我使用打字器的同步功能

在回收期间:

imageData.toString('base64')

我取回了原始的base64字符串,可以作为图像插入网页

最新更新