Skip to content

Instantly share code, notes, and snippets.

@chungquantin
Created November 25, 2020 11:21
Show Gist options
  • Select an option

  • Save chungquantin/5f464c34084c5a20921e281c96cf71ca to your computer and use it in GitHub Desktop.

Select an option

Save chungquantin/5f464c34084c5a20921e281c96cf71ca to your computer and use it in GitHub Desktop.
Mongo File Upload GridFS
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
const path = require('path');
const util = require('util');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const storage = new GridFsStorage({
url: process.env.MONGO_URI,
options: { useNewUrlParser: true, useUnifiedTopology: true },
file: (req, file) => ({
bucketName: 'images',
filename: `${
Date.now() + Math.floor(Math.random() * 1000000)
}-dakonet-${file.originalname}`,
}),
});
const uploadFile = multer({
storage,
limits: {
fileSize: 4 * 1024 * 1024,
},
fileFilter(req, file, cb) {
const ext = path.extname(file.originalname);
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg') {
req.fileValidationError = 'Forbidden extension';
return cb(null, false, req.fileValidationError);
}
cb(null, true);
},
}).array('file', 6);
module.exports = util.promisify(uploadFile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment