【问题标题】:how upload image to mongodb buffer with react in client side如何将图像上传到 mongodb 缓冲区并在客户端做出反应
【发布时间】:2019-10-03 16:17:13
【问题描述】:

我正在使用 multer

  const upload = multer({
    limits: {
        fileSize: 1000000
    },
    fileFilter(req, file, cb) {
        if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
            return cb(new Error('Please upload an image'))


        cb(undefined, true)
    }
})

服务器端,使用 express 和 multer 我想将图像以缓冲区类型存储到 mongodb


router.post('/users/me/avatar', auth, upload.single('avatar'), async (req, res) => {
    console.log(req.file)
    const buffer = await sharp(req.file.buffer).resize({ width: 250, height: 250 }).png().toBuffer()
    req.user.avatar = buffer
    await req.user.save()
    res.send()
}, (error, req, res, next) => {
    res.status(400).send({ error: error.message })
})

【问题讨论】:

    标签: node.js reactjs mongodb express buffer


    【解决方案1】:

    你想要你的图片在 base 64 吗?你需要使用Jimp

    npm install --save jimp

    const Jimp = require('jimp');
    
    Jimp.read(req.file.path)
      .then(image => {
        return image.getBase64(Jimp.AUTO, (err, res) => {
          if (err) return console.log(err);
    
          // you launch your mongodb save with res
          return res; 
        });
      })
      .catch(err => console.log(err));
    

    https://github.com/oliver-moran/jimp/issues/522#issuecomment-411246785

    【讨论】:

    • 我认为这是一个服务器端代码我上面已经有我的代码我使用 multer 和 sharp 来调整图像大小,我在邮递员中对其进行了测试,它完美地工作只是想实现一个客户端对此做出反应我不知道如何在客户端将图像转换为缓冲区类型并将其保存在mongodb中?
    • 您无法从客户端访问 mongoDB,这是不可能的。你是在告诉我你已经在你的前端打开了后端路由???是的,只要您不使用 react-router 就可以。试试我的代码。
    【解决方案2】:
    const imageMimeTypes = ['image/jpeg', 'image/png', 'image/jif']
    
    function saveCover(book, cover) {
        if(cover == null) return
        if(cover != null && imageMimeTypes.includes(cover.type)) {
            book.coverImage = new Buffer.from(cover.data, 'base64')
            book.coverImageType = cover.type
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-26
      • 2020-10-18
      • 1970-01-01
      • 2021-06-17
      • 2021-02-04
      • 2019-07-08
      • 2019-08-01
      • 1970-01-01
      • 2013-10-27
      相关资源
      最近更新 更多