fastify.get('/gallery/:id', async (request, reply) => {
const response = await gallery.findOne({ _id: ObjectId(request.params.id) })
if (!response || response === null) {
reply.status(404).send('not found')
}
// ------------------------------------
const binary = response.file.data;
const bufferImage = iconv.encode(binary, 'binary').toString('base64');
const buffer = Buffer.from(bufferImage, "base64")
console.log(__dirname, buffer.byteLength, bufferImage.slice(0, 20))
reply.status(200).header('Content-Type', 'stream');
writeFile(path.join(__dirname, '../uploads/', 'pic.png'), buffer, (err) => {
if (err) throw err;
console.log("The file has been saved!");
});
})
使用MongoDB存储图像,而不是GridFS
,因为图像将被限制为5mb,MongoDB文档的结构如下:
{
"_id": {
"$oid": "64088bf75250bb1ec5b72294"
},
"file": {
"name": "jeremiinstitute.png",
"data": {
"$binary": {
"base64": "iVBORw0KGgoAAAANSUhEUgAABdwAAAH6CAYAAAAdj45cAAG0r0lEQVR42uzdTWhcVRiH8Xeklpgmc8/MPefemfuRQCt2pSCiVNukk5lMkpl8F...",
"subType": "00"
}
},
"size": 111848,
"encoding": "7bit",
"tempFilePath": "",
"truncated": false,
"mimetype": "image/png",
"md5": "572fc35e74f2d8772fd7ef47c748330e"
},
"public": true,
"date": "2023-03-08T13:20:41.612Z"
}
我正在使用incov-lite
npm软件包将图像二进制转换为缓冲区。但是图像没有显示,或者看起来被损坏了。我做错了什么吗?
1条答案
按热度按时间taor4pac1#
看来我经历了额外的不必要的步骤。谢谢你@ManuelSpigolon