Last active
September 12, 2020 00:57
-
-
Save tgmarinho/c8af8c47a30bf7ea48e6c77dce63cdd9 to your computer and use it in GitHub Desktop.
This file contains 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 multer = require("multer"); | |
const path = require("path"); | |
const crypto = require("crypto"); | |
const aws = require("aws-sdk"); | |
const multerS3 = require("multer-s3"); | |
const MAX_SIZE_TWO_MEGABYTES = 2 * 1024 * 1024; | |
const storageTypes = { | |
local: multer.diskStorage({ | |
destination: (req, file, cb) => { | |
cb(null, path.resolve(__dirname, "..", "..", "tmp", "uploads")); | |
}, | |
filename: (req, file, cb) => { | |
crypto.randomBytes(16, (err, hash) => { | |
if (err) cb(err); | |
file.key = `${hash.toString("hex")}-${file.originalname}`; | |
cb(null, file.key); | |
}); | |
}, | |
}), | |
s3: multerS3({ | |
s3: new aws.S3(), | |
bucket: process.env.BUCKET_NAME, | |
contentType: multerS3.AUTO_CONTENT_TYPE, | |
acl: "public-read", | |
key: (req, file, cb) => { | |
crypto.randomBytes(16, (err, hash) => { | |
if (err) cb(err); | |
const fileName = `${hash.toString("hex")}-${file.originalname}`; | |
cb(null, fileName); | |
}); | |
}, | |
}), | |
}; | |
module.exports = { | |
dest: path.resolve(__dirname, "..", "..", "tmp", "uploads"), | |
storage: storageTypes[process.env.STORAGE_TYPE], | |
limits: { | |
fileSize: MAX_SIZE_TWO_MEGABYTES, | |
}, | |
fileFilter: (req, file, cb) => { | |
const allowedMimes = [ | |
"image/jpeg", | |
"image/pjpeg", | |
"image/png", | |
"image/gif", | |
]; | |
if (allowedMimes.includes(file.mimetype)) { | |
cb(null, true); | |
} else { | |
cb(new Error("Invalid file type.")); | |
} | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment