• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

89
Vistas
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.

almost 3 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda