如何将多个文件上传到mongodb

时间:2019-07-06 10:16:41

标签: node.js mongodb gridfs

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

我知道要上传单个文件,您必须将其称为functios

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 package page中有这样的例子

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) => {
    /*....*/ 
})

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

1 个答案:

答案 0 :(得分:0)

我找到了要搜索的内容,


// 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) => {
    /*....*/ 
})