在Nest.js中,如何在我的API响应中提供与我的JSON对象捆绑在一起的静态内容文件

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

在我的Nest.js API中,我有一个GET,必须在Response中返回一个db行,以及(最多)6个图像文件(base64编码)。

我能做的是:

db中的6列包含唯一的文件名(实际图像位于名为“image-uploads”的文件夹中),并且与路径一起我可以使用@Res装饰器将其中任何一个发送回去,例如

@Get('/findVehicleEntry/:id')
async findVehicleEntry(@Param('id') id: number, @Res() res) {
    const resVehicle: Vehicle = await this.vehiclesService.findVehicleEntry(id);
    if (resVehicle) {
        res.sendFile(resVehicle.photo1, { root: 'image-uploads' });
    }
}

以上成功下载了一个图像文件作为Content-Type:“application / octet-stream”

我的计划是(以及我不知道该怎么做):

首先,从文件夹中获取图像并进入变量,然后在其上运行base64编码,然后将resVehicle.photo1设置为等于该base64字符串,并对其他5个图像执行相同操作,然后执行res.send(resVehicle) );

像这样的东西:

@Get('/findVehicleEntry/:id')
    async findVehicleEntry(@Param('id') id: number, @Res() res) {
    const resVehicle: Vehicle = await this.vehiclesService.findVehicleEntry(id);
    if (resVehicle) {
        let image = something.get('resVehicle.photo1', 'my/path/to/image-uploads');
        image = Buffer.from(image).toString('base64');
        resVehicle.photo1 = image;
        // do the same for the other 5 images
        res.send(resVehicle);
    }
}

这是我第一次使用Nest / Express / Node,实际上这是我写的第一个API,所以我的想法/设计可能完全不合适。欢迎任何建议。非常感谢。

编辑:一直在阅读大文件的base64编码不是一个好主意。我很高兴放弃base64的想法,主要问题是如何将我的db row JSON对象和6个图像放到同一个Response中?

typescript express api-design
1个回答
0
投票

你是正确的,图像的base64编码不是一个好主意。

这里的传统解决方案是:您不推送图像,在json响应中提供图像路径,让API使用者使用路径获取图像。

  • 将实际图像文件保存在公共文件夹中,而不是数据库中。这意味着它应该可以从浏览器访问,例如yourdomain.com/images/image232.jpg
  • 在您的数据库中,将这些图像的路径存储为字符串(image1: "yourdomain.com/images/image232.jpg"
  • 提供包含路径的json响应({make:"Toyota", image1:"yourdomain.com/images/image232.jpg"}
  • 无论谁使用您的API,都可以使用该路径来获取图像。
© www.soinside.com 2019 - 2024. All rights reserved.