1 year ago
#77498
Luiz Alves
Set Multer object key in node.js on the fly
I have node express routes, where I need to set a aws bucket name in a Multer Object.
When the users get logged in my app, I have an API to get the correct bucket name to user. I call that API in a middleware to all routes and I set req.folder_do_bucket='XXXX' from API result.
After that, when the user access others routes such as below, I need to set the bucket in the Multer Object. But, my problem is that "req" is not available to set it in the Multer.
Maybe I can create the multer object into the route, but I am not sure if this is a better solution, because I will have to do it in all routes(get, post....)
How could I solve it?
const express = require("express");
const router = express.Router();
const multer = require("multer");
const aws = require("aws-sdk");
const s3 = new aws.S3();
const multerS3 = require("multer-s3");
const storageImagemClienteS3 = multerS3({
s3: s3,
bucket: req.folder_do_bucket, // AWS_BUCKET_NAME -->Here is my problem, req is not available here
contentType: multerS3.AUTO_CONTENT_TYPE,
acl: "public-read",
key: (req, file, cb) => {
const fileName =
`${req.conta}/clientes/cliente-${req.params.id}/imagens/` +
file.originalname;
cb(null, fileName);
},
});
console.log(storageImagemClienteS3);
const uploadImagemClienteS3 = multer({
storage: storageImagemClienteS3,
limits: { fileSize: MAX_SIZE },
fileFilter: function (req, file, cb) {
checkFileTypeImage(file, cb);
},
}).single("file");
router.post("/upload/:id", function (req, res) {
if (!req.params.id || req.params.id == "undefined") {
return res
.status(400)
.send({ message: "Um erro ocorreu selecionando cliente" });
}
uploadImagemClienteS3(req, res, async (err) => {
if (err) {
....
} else {
......
}
});
});
node.js
express
multer-s3
0 Answers
Your Answer