在我的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中?
你是正确的,图像的base64编码不是一个好主意。
这里的传统解决方案是:您不推送图像,在json响应中提供图像路径,让API使用者使用路径获取图像。
yourdomain.com/images/image232.jpg
image1: "yourdomain.com/images/image232.jpg"
){make:"Toyota", image1:"yourdomain.com/images/image232.jpg"}
)