首页 > 解决方案 > 如何将多个文件上传到mongodb

问题描述

我正在尝试使用gridfsand将多个文件上传到 mongo db multer

我知道要上传单个文件,您必须调用此函数

const conn = mongoose.connection;
const mongoURI = "mongodb://localhost:27017/moto_website";

// Init gfs
let gfs;

conn.once('open', () => {
    // Init stream
    gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection('uploaded_images'); //collection name
});

// Create storage engine
const storage = new GridFsStorage({
  url: mongoURI,
  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: 'uploaded_images' //collection name
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({ storage });

router.post('/posts', upload.single('file'), (req, res) => {...})

所以当upload.single(<file_name>)被称为文件上传时,但我怎样才能上传多个文件?

multer-gridfs-storage npm 包页面中有这个例子

const sUpload = upload.single('avatar');
app.post('/profile', sUpload, (req, res, next) => { 
    /*....*/ 
})

const arrUpload = upload.array('photos', 12);
app.post('/photos/upload', arrUpload, (req, res, next) => {
    /*....*/ 
})

const fUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', fUpload, (req, res, next) => {
    /*....*/ 
})

我应该使用哪一个以及我应该通过哪些参数?

标签: node.jsmongodbgridfs

解决方案


我找到了我正在寻找的东西,


// use this one for upload a single file

const sUpload = upload.single('avatar'); // avatar is the name of the input[type="file"] that contains the file
app.post('/profile', sUpload, (req, res, next) => { 
    /*....*/ 
})

// use this one for upload an array of files 
// You have an array of files when the input[type="file"] has the atribute 'multiple'

const arrUpload = upload.array('photos', 12); // photos is the name of the input[type="file"] that contains the file
app.post('/photos/upload', arrUpload, (req, res, next) => {
    /*....*/ 
})

// use this one for upload multipe input tags
// {name: <name of the input>, maxCount: <the number of files that the input has>}

const fUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', fUpload, (req, res, next) => {
    /*....*/ 
})

推荐阅读