Search code examples
node.jsexpressmulter

Upload Images to Web Server directory using Multer [Nodejs]


I am upload images using multer and Nodejs. The upload works perfectly. The problem is I want to upload those images directly to a folder inside wwwroot folder of the IIS Webserver.

var Storage = multer.diskStorage({
    destination: function (req, file, callback) {
       // callback(null, "../grit-server/uploads/");
       callback(null, "https://example.com/grit/images/photogallery/");
    },
    
    filename: function (req, file, callback) {
        const sqc = sqlConn;
        var fileNames = (file.originalname.split('_'))
        let query = 'INSERT INTO dbo.MS_PhotoGallery (MinorId,Photo_Name) VALUES (@MinorId,@PhotoName)'
        let params = [
            sqc.paramize('MinorId', fileNames[1], sql.Int()),
            sqc.paramize('PhotoName',fileNames[2], sql.VarChar(255))
        ]
       sqc.SqlExecuteStatementCallback(
            query,params,(result)=>{
                res.send(result)
            }
       )
        callback(null, file.originalname);
    }
});

The above code is of the Multer storage where I am setting the URL where to upload the images. But it is throwing error

'Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client'

What modifications shall I do to upload the images in the URL mentioned under Storage to save any photos in the location.


Solution

  • I have solved this problem hardcoding the path like '../../../../wwwroot/abc/def/'. This is not the efficient way but it works for my specific problem as the images folder is not going to change in future.