Search code examples
node.jsexpressfile-uploadmulter

how to create year/month/day structure when uploading files with nodejs multer?


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);
    }
});

Solution

  • You can create a custom function using fs library functions,

    • initialize fs lib
    const fs = require("fs");
    
    • create a method to return date path on the base of input param current date
    • ex:
      • input: new Date()
      • return: "2021/6/27"
    function getDatePath(date) {
        return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
    }
    
    • create directory recursive if it does not exist, can handle with try-catch block
    function getDirPath(dirPath) {
        try {
            if (!fs.existsSync(dirPath)) fs.promises.mkdir(dirPath, { recursive: true });
            return dirPath;
        } catch (error) {
            console.log(error.message);
        }
    }
    
    • use the above method in destination
    //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);
        }
    });