Reputation: 376
I am using Multer and Express to upload, via an Ajax, a list of images that I put in a blob. I can receive and save these images on the server side. The problem is that I need that all the images of the same Ajax request to be inside the same folder. I want one folder by request. Each folder has random uuid name.
The problem is that each image gets in a different folder. Maybe the problem is beacuase I send the images in a blob? Do you have an idea to solve this? Thank you very much, here's my configuration of multer:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
let path = './public/images/' + uuidv4() + '/'; //a different folder for each request
file.path = path;
fs.mkdirSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '.' + mime.extension(file.mimetype));
}
})
let upload = multer({ storage: storage });
Upvotes: 0
Views: 1255
Reputation: 1521
The problem is that the destination
function is run for each image of the request, which will create a different UUID each time, thus create a new folder for each image.
You need to store the UUID in the req
beforehand, so you can use it in the destination
function. This will create an unique directory for each request.
const storage = multer.diskStorage({
destination: function (req, file, cb) {
let path = './public/images/' + req.imagesFolder + '/';
file.path = path;
fs.mkdirSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '.' + mime.extension(file.mimetype));
}
})
const upload = multer({ storage: storage });
And, when using the middleware :
const preuploadMiddleware = (req, res, next) => {
req.imagesFolder = uuidv4();
next();
};
app.post('/images', preuploadMiddleware, upload, (req res, next) => {
// ...
});
Upvotes: 4