Skip to content

Instantly share code, notes, and snippets.

@hay-wire
Created October 3, 2018 17:44
Show Gist options
  • Save hay-wire/8f328894a1fad2abacfe93fac0bca0c5 to your computer and use it in GitHub Desktop.
Save hay-wire/8f328894a1fad2abacfe93fac0bca0c5 to your computer and use it in GitHub Desktop.
File uploading with multer and express
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