Created
October 3, 2018 17:44
-
-
Save hay-wire/8f328894a1fad2abacfe93fac0bca0c5 to your computer and use it in GitHub Desktop.
File uploading with multer and express
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
const express = require('express'); | |
const router = express.Router(); | |
const multer = require('multer'); | |
const path = require('path'); | |
const debug = require('debug')('myNameSpace'); | |
const ALLOWED_IMAGE_TYPES = ['png', 'jpg', 'gif']; | |
const publicFilesDestination = path.join('public', 'static', 'uploads', '/'); | |
let fileStorage = multer.diskStorage({ | |
destination: function (req, file, cb) { | |
debug("file path: ", publicFilesDestination); | |
cb(null, publicFilesDestination); | |
}, | |
filename: function (req, file, cb) { | |
let ext = path.extname(file.originalname).toLowerCase(); | |
if (ALLOWED_IMAGE_TYPES.indexOf(ext) < 0) { | |
return cb('INVALID_FILETYPE'); | |
} | |
let filepath = publicFilesDestination; | |
let filename = file.fieldname + '-' + Date.now() + ext; | |
debug("renamed file: ", filepath + filename); | |
cb(null, filename); | |
} | |
}); | |
let fileHandler = multer({ | |
storage: fileStorage | |
}); | |
router.post("/my/route/here", fileHandler.any(), myController.doSomething); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment