I want to upload the file using multer into folder structure with year/month/day. Like upload/2021/06/27/filename. How can I do that?
//configuring multer storage for images
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'upload/');
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString().replace(/:/g, '-') + '-' + file.originalname);
}
});
You can create a custom function using fs
library functions,
const fs = require("fs");
new Date()
function getDatePath(date) {
return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
}
function getDirPath(dirPath) {
try {
if (!fs.existsSync(dirPath)) fs.promises.mkdir(dirPath, { recursive: true });
return dirPath;
} catch (error) {
console.log(error.message);
}
}
//configuring multer storage for images
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, getDirPath('upload/' + getDatePath(new Date())));
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString().replace(/:/g, '-') + '-' + file.originalname);
}
});