I am uploading images to Amazon S3 with Multers3 and express. The Image is uploading but I am facing challenges uploading images to the Right Path.
For example, before integrating Multer with s3, with this code, the image will be uploaded to public/uploads/postImages/the new filename.jpg
const uploadPath = path.join('public', Post.postImageBasePath)
const imageMineTypes = ['image/jpeg', 'image/png', 'image/gif']
const upload = multer({
dest: uploadPath,
fileFilter: (req, file, callback) => {
callback(null, imageMineTypes.includes(file.mimetype) )
}
})
But after integrating Multer with Amazon S3, with this code, the image is now being uploaded to public/uploads/postImages/original file name.jpg
const uploadPath = path.join('public', Post.postImageBasePath)
const upload = multer({
storage: multerS3({
s3: s3,
bucket: bucketname,
s3BucketEndpoint:true,
endpoint:"http://" + bucketname + ".s3.amazonaws.com",
key: function (req, file, cb) {
cb(null, uploadPath + '/' + file.originalname);
}
})
})
If I want to get the new file name then I can do something like this
req.file.filename
but this is only possible inside my upload and that is after the image has been successfully uploaded. if try to do it inside the above code it will show undefined, because the new file name has not yet been generated. below is my code for upload.
router.post('/', upload.single('cover'), async (req, res, next) => {
const fileName = req.file != null ? req.file.filename : null
const post = new Post({
title: req.body.title,
description: req.body.description,
from: req.body.from,
postImage: fileName
})
try {
const newPost = await post.save()
res.redirect('/posts')
} catch {
if (post.postImage != null) {
removePostImage(post.postImage)
}
renderNewPage(res, post, true)
}
});
How do I add dest: uploadPath,
path with S3? so that the path will be
public/uploads/postImages/new file name.jpg
This is what i want to achieve
const uploadPath = path.join('public', Post.postImageBasePath)
const imageMineTypes = ['image/jpeg', 'image/png', 'image/gif']
const upload = multer({
storage: multerS3({
dest: uploadPath,
s3: s3,
bucket: bucketname,
s3BucketEndpoint:true,
endpoint:"http://" + bucketname + ".s3.amazonaws.com",
key: function (req, file, cb) {
cb(null, uploadPath + '/' + req.file.filename);
},
fileFilter: (req, file, callback) => {
callback(null, imageMineTypes.includes(file.mimetype) )
}
})
})
In Summary, I want the image path to be the new image name that has been generated