如何将多个图像上传到mongoDB?

时间:2019-01-19 12:39:46

标签: mongodb multer gridfs

我成功编写了代码,可以将图像上传文件上传到MongoDB中。但是现在我想将多个图像上传到数据库。我用了gridFS和multer。有人可以帮我解决这个问题

// Create Storage engine
var storage = new GridFsStorage({
url: Mongo,
file: (req, file) => {
return new Promise((resolve, reject) => {
  crypto.randomBytes(16, (err, buf) => {
    if (err) {
      return reject(err);
    }
    const filename = buf.toString('hex') + path.extname(file.originalname);
    const fileInfo = {
      filename: filename,
      bucketName: 'uploads',
      metadata: {'username': req.body.username}
  };
    resolve(fileInfo);
  });
  });
  }
  });
  const upload = multer({ storage });

  /*--------------------------------------------------------*/


 app.get('/',(req,res)=>{
 gfs.files.find().toArray((err,files)=>{
// Check if Files
if(!files || files.length ===0)
{
  res.render('index',{files:false});
} else{
  files.map(file=>{
    if(file.contentType === 'image/jpeg' || file.contentType === 
 'image/png')
    {
      file.isImage = true;
    } else {
      file.isImage = false;
    }
  });
  res.render('index',{files:files});

}

});
});

/*----------------------------------------------------*/


// Display Image
 app.get('/image/:filename', (req,res)=>{
 gfs.files.findOne({filename: req.params.filename}, (req,file) =>{
  // Check if File
  if(!file || file.length ===0)
 {
  return res.status(404).json({
    err: 'No files exist'
  });
  }
  // Check if image
  if(file.contentType === 'image/jpeg' || file.contentType === 'image/png')
  {
  // Read output tp browser
  var readstream = gfs.createReadStream(file.filename);
  readstream.pipe(res);
 }
 else
 {
  res.status(404).json({
    err: 'Not an image'
  });
  }
 });
});

我附加了与图像上传有关的代码部分。请检查此代码,并给出一个很好的技巧,将多个图像上传到mongoDB

0 个答案:

没有答案