最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin14浏览0评论

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

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

我正在使用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 })
})
回答如下:

您想要以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/oliver-moran/jimp/issues/522#issuecomment-411246785

发布评论

评论列表(0)

  1. 暂无评论