NodeJS fs.writeFile未按预期工作,映像似乎已损坏

btxsgosb  于 2023-03-12  发布在  Node.js
关注(0)|答案(1)|浏览(134)
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软件包将图像二进制转换为缓冲区。但是图像没有显示,或者看起来被损坏了。我做错了什么吗?

taor4pac

taor4pac1#

fastify.get('/gallery/:name', async (request, reply) => {
        // const response = await gallery.findOne({ _id: ObjectId(request.params.id) })
        const response = await gallery.findOne({ 'file.name': request.params.name })
        if (!response || response === null || response.public === false) {
            return reply.status(404).send('not found');
        }
        // ------------------------------------
        const binary = JSON.stringify(response.file.data);
        const buffer = Buffer.from(binary, "base64")
        
        reply.status(200).header('Content-Type', response.mimetype);
        return reply.send(buffer)
    })
{
  "_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"
}

看来我经历了额外的不必要的步骤。谢谢你@ManuelSpigolon

相关问题