Как загрузить несколько файлов на mongodb - PullRequest
0 голосов
/ 06 июля 2019

Я пытаюсь загрузить несколько файлов в mongo db, используя gridfs и 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) => {
    /*....*/ 
})

Какой из них мне следует использовать и какие аргументы я должен передать?

1 Ответ

0 голосов
/ 07 июля 2019

Я нашел то, что искал,


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