Created
November 25, 2020 11:21
-
-
Save chungquantin/5f464c34084c5a20921e281c96cf71ca to your computer and use it in GitHub Desktop.
Mongo File Upload GridFS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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