Typescript 在Nest.js中,如何在API响应中将静态内容文件与我的JSON对象捆绑在一起
在我的Nest.js API中,我有一个GET,它必须在响应中返回一个db行,以及(最多)6个图像文件(base64编码) 我能做的是: db中的6列包含唯一的文件名(实际图像位于名为“image uploads”的文件夹中),连同路径,我可以使用@Res decorator将其中任何一个发送回,例如Typescript 在Nest.js中,如何在API响应中将静态内容文件与我的JSON对象捆绑在一起,typescript,express,api-design,Typescript,Express,Api Design,在我的Nest.js API中,我有一个GET,它必须在响应中返回一个db行,以及(最多)6个图像文件(base64编码) 我能做的是: db中的6列包含唯一的文件名(实际图像位于名为“image uploads”的文件夹中),连同路径,我可以使用@Res decorator将其中任何一个发送回,例如 @Get('/findVehicleEntry/:id') async findVehicleEntry(@Param('id') id: number, @Res() res) { co
@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' });
}
}
上面成功下载了一个图像文件作为内容类型:“应用程序/八位字节流”
我的计划是(我不知道怎么做):
首先,从文件夹中获取图像并放入变量,然后对其运行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行JSON对象和6个图像得到相同的响应?你是对的,图像的base64编码不是一个好主意 这里的传统解决方案是: 您不推送图像,而是在json响应中提供图像路径,并让API使用者使用该路径获取图像
- 将实际图像文件保存在公开可用的文件夹中,而不是数据库中。这意味着它应该可以通过浏览器访问,例如
yourdomain.com/images/image232.jpg
- 在数据库中,将这些图像的路径存储为字符串(
)image1:“yourdomain.com/images/image232.jpg”
- 提供包含路径的json响应(
){make:“Toyota”,image1:“yourdomain.com/images/image232.jpg”}
- 然后,无论谁使用您的API,都可以使用该路径获取图像