Skip to content

Instantly share code, notes, and snippets.

@lazycipher
Created November 26, 2020 13:43
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 lazycipher/dceb84665ecb8306ace7e777315df1b1 to your computer and use it in GitHub Desktop.
Save lazycipher/dceb84665ecb8306ace7e777315df1b1 to your computer and use it in GitHub Desktop.
upload to aws using multer and multers3
const s3Config = new aws.S3({
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_KEY,
// sessionToken:'', // In most of the cases it's not needed. If using AWS Educate, you'll need this.
region: process.env.AWS_STORAGE_REGION
})
const multerS3Config = multerS3({
s3: s3Config,
bucket: process.env.AWS_BUCKET_NAME,
metadata: function (req, file, cb) {
cb(null, { fieldName: file.fieldname });
},
acl: 'public-read',
key: function (req, file, cb) {
cb(null, new Date().toISOString() + '-' + file.originalname)
}
})
// type of files allowed
const fileFilter = (req, file, cb) => {
if (file.originalname.match(/\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$/)) {
cb(null, true)
} else {
cb(null, false)
}
}
exports.upload = multer({
storage: multerS3Config,
limits: {
fileSize: 1024 * 1024 * 10 // 10 mb
},
fileFilter: fileFilter,
upload: (err) => {
if (err instanceof multer.MulterError) {
throw new Error('error in uploading ' + err)
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment