Mat.C
Mat.C

Reputation: 1429

How to upload multiple files to mongodb

I'm trying to upload multiple files to mongo db using gridfs and multer.

I know that for upload a single file you have to call this 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) => {...})

so when the upload.single(<file_name>) is called the file is uploaded, but how can i upload multiple files?

In the multer-gridfs-storage npm package page there are this examples

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

Which one should i use and what argouments i should pass?

Upvotes: 1

Views: 3333

Answers (1)

Mat.C
Mat.C

Reputation: 1429

I found what i was searching for,


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

Upvotes: 1

Related Questions