如何在客户端做出反应将图像上传到mongodb缓冲区

时间:2019-10-03 16:17:13

标签: node.js reactjs mongodb express buffer

我正在使用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)
    }
})

服务器端,使用快速和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 })
})

2 个答案:

答案 0 :(得分:0)

您要以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

答案 1 :(得分:0)

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
    }
}