【问题标题】:Using GridFS-Stream to send image file to Front-End React.js through Axios - Converting chunk to string base64使用 GridFS-Stream 通过 Axios 将图像文件发送到前端 React.js - 将块转换为字符串 base64
【发布时间】:2020-02-03 07:25:54
【问题描述】:

所以我已经使用 Multer 和 Multer-Gridfs-Storage 成功地将我的图像文件下载到了我的 MongoDB,但是我无法检索它。

当我尝试使用 GridFS-Stream 检索数据时,它像上一个问题一样返回: GridFS : How to display the result of readstream.pipe(res) in an <img/> tag?

当我使用这段代码时,发送到我的前端的只是集合中的第一个块,但它实际上是可用的。

const readstream = gfs.createReadStream({ filename: files[0].filename });

readstream.on('data', (chunk) => {
    res.send({ image: chunk.toString('base64') })              
})

我怎样才能取回所有的块?我应该放弃并开始使用 GridFSBucket 吗?

【问题讨论】:

  • GridFS 是一种驱动机制,用于存储大块数据(大于 BSON 文档的 16MB 限制),方法是将数据分布在多个文档中。如果您认为您想将使用 GridFS 存储的图像作为 base64 字符串返回,那么您做错了几件事。可以肯定的是,您的图像都没有超过 16MB。如果他们这样做了,那么你would not base64 encode them.

标签: reactjs mongodb express axios gridfs-stream


【解决方案1】:

我最终尝试了这个,它成功了!

            let data = ''
            readstream.on('data', (chunk) => {
                data += chunk.toString('base64')
            })
            readstream.on('end', () => {
                res.send(data)
            })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2014-09-14
    • 2018-09-07
    • 2014-07-21
    • 1970-01-01
    • 2013-02-15
    相关资源
    最近更新 更多