Search code examples
node.jsfile-uploadmultercreate-directory

How to create folder automatically before files upload via multer so that those files get stored in that created folder in nodejs?


This is my multer code to upload multiple files.

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/files/'+ req.user.id)
  },
  filename: function (req, file, cb) {
    x = file.originalname; //+path.extname(file.originalname);
  cb(null,x);
  }
});

var upload = multer({storage: storage});

This is the post request where files get submitted on click submit.

router.post(upload.array("FileUpload",12), function(req, res, next) {

//Here accessing the body datas.

})

So what I want is that, I want to create a folder first with the name of the ID generated which can be access from the req.body and then upload those files into that folder respectively. But since I cannot access the body first before upload I am unable to create that respective folder directory. Is there any other way around which I can think of and implement this?

Updated Solution using fs-extra package.

const multer = require('multer');
let fs = require('fs-extra');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let Id = req.body.id;
    fs.mkdirsSync('./public/files/'+ req.user.id + '/' + Id);
    cb(null, './public/files/'+ req.user.id + '/' + Id)
  },
  filename: function (req, file, cb) {
    x = file.originalname; //+path.extname(file.originalname);
  cb(null,x);
  }
});

var upload = multer({storage: storage});

This is the post request where files get submitted on click submit.

router.post(upload.array("FileUpload",12), function(req, res, next) {

//Here accessing the body datas.

})

Solution

  • you have to install first the fs-extra which will create folder

    create seprate folder for multer like multerHelper.js

    const multer = require('multer');
    let fs = require('fs-extra');
    
    let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        let Id = req.body.id;
        let path = `tmp/daily_gasoline_report/${Id}`;
        fs.mkdirsSync(path);
        cb(null, path);
    },
    filename: function (req, file, cb) {
        // console.log(file);
    
        let extArray = file.mimetype.split("/");
        let extension = extArray[extArray.length - 1];
        cb(null, file.fieldname + '-' + Date.now() + "." + extension);
     }
    })
    
    let upload = multer({ storage: storage });
    
    let createUserImage = upload.array('images', 100);
    
    let multerHelper = {
        createUserImage,
    }
    
    module.exports = multerHelper;
    

    in your routes import multerhelper file

    const multerHelper = require("../helpers/multer_helper");
    
    router.post(multerHelper , function(req, res, next) {
    
    //Here accessing the body datas.
    
    })