Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Attempting to create custom directory during image upload with Multer

I am attempting to create a directory based on the body of the request. Here is the code:

const storage = multer.diskStorage({
    destination: function(request, file, callback) {  
        let userUploadDir = uploadDir + '/' + request.body.user + '/' + request.body.address;
        fs.access(userUploadDir, async (err) => {
            if (err) {
                await fs.promises.mkdir(userUploadDir, { recursive: true });
            }
        }); 
        callback(null, userUploadDir);
    },

    filename: function(request, file, callback) {
        let date = new Date();
        let stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "-" + date.getHours() + "-" + date.getMinutes();
        let newFileName = stringDate + "-" +  file.originalname;
        callback(null, newFileName);
    },

    fileFilter: function(request, file, callback) {
        let ext = path.extname(file.originalname);
        if (ext !== ".png" && ext !== ".jpg" && ext !== ".jpeg" && ext !== ".webp") {
            return callback(new Error("Only images are allowed"));
        }
        callback(null, true);
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 5
    }
});

router.post("/image", upload.fields([{ name: 'file', maxCount: 3 }]), async (request, response, next) => {
     response.json({
         "message":"Successful file uploaded."
     })
}

My issue is that when this code is run, it will create the directory, but the file will not save to it and I cannot figure out what I am doing wrong here.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!