Skip to content

Instantly share code, notes, and snippets.

@tgmarinho
Last active September 12, 2020 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgmarinho/c8af8c47a30bf7ea48e6c77dce63cdd9 to your computer and use it in GitHub Desktop.
Save tgmarinho/c8af8c47a30bf7ea48e6c77dce63cdd9 to your computer and use it in GitHub Desktop.
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