'Access res.locals in Multer.diskStorage->filename

I'm working on a login, where the use consists of userImage, userName, userStatus (all send as form-data). To upload the userImage im using Multer. This is how my route looks like

router.post('/create', upload.any(), createUser, upload.single('userImage'));

upload.any() This im calling so that I can retrieve the userName & userStatus from the form-data body, which can't be accessed via req.body otherwise

createUser Is my middleware to create the User which looks like this

        var savedUser = await user.save();
        var createdUserId = savedUser._id;  // use this to add to the profile Image's name 

        var imgExtension = path.extname(req.body.userImage)
        var imgPath = `./images/profileImages/${createdUserId}_profileImage${imgExtension}`
        
        //now update the newly created user with its image 
        await userModel.updateOne({_id: createdUserId},{
            image: {
                path: imgPath,
                contentType: `image/${imgExtension}`  
            }
        });
        // to use in Multer middleware
        res.locals.imgName = String(`${createdUserId}_profileImage${imgExtension}`)

        res.status(201).json({
            message: "User has been saved",
            userId: createdUserId
        });        
        
        next()

So Im using mongoDB, after creating the user in the Database Im getting the ObjectID which I want to be included in the image name, only the path to the image is being saved on the server.

Now I'm trying to pass the imgName as res.locals.imgName to the Multer middleware so that I can store it on the server.

var storage = multer.diskStorage({
    destination: (req, file, cb) =>{
        cb(null, './images/profileImages')
    },
    filename: (req , file, cb) => {
        const imgName = req.res.locals.imgName // HERE LIES THE PROBLEM
        cb(null, `${imgName}`)
    }
});
export var upload = multer({ storage: storage});

[if there is a typo in the code that I missed it's only because I couldn't copy and paste it to the Stackoverflow code-field, nodejs needs ` <- this symbol so that it can access variables in a String ]

So on the Database everything works out fine, all the information is saved correctly.

Now the Image is being saved on the server but as undefined, if I add a .png after the undefined I can also view the image.

I need a way to access the res.locals.imgName variable in Multer filename. Here I found something similar

one user said res.locals.something can be accessed via req.res, he didn't say anything else so I tried every combination of req.res.res.locals.imgName to req.res.imgName and it's always undefined or doesn't work altogether.

So is there a way to solve this or do I have to MacGyver some workaround.



Solution 1:[1]

req.res.locals works for me

const profilePicStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './user-profile-pictures/');
    },
    filename: function (req, file, cb) {
        cb(null, req.res.locals.authenticatedUserId)
    }
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Florian Walther