1

I have a main express route that once navigated to, should prompt a download of the specified file in res.download:

app.get('/download/:fileid', (req, res) => {
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'filesystem'
      });

    connection.connect(() => {
        console.log("Connection to database established");

    });
    connection.query(`SELECT * from files where fileid = '${req.params.fileid}'`, (error, results, fields) => {
        if (error) throw error;
        else if(results.length === 0){
            console.log("empty");
        }
        else{
            res.download(`./uploads/PFSk5x7bg.png`, 'PFSk5x7bg.png', (err) => {
                console.log(err);
            })
        }
    });

    connection.end();
})

However, when accessed, it simply displays the image on the webpage, and when I check the response headers, the content disposition header is missing. I have tried manually setting it with res.setheader, but still does not work.

I tried making another route just for testing:

app.get('/test', (req, res) => {
    res.download(`./uploads/PFSk5x7bg.png`, 'PFSk5x7bg.png', (err) => {
        console.log(err);
    })
})

and it works.... the content disposition header is there, the browser actually downloads the file.

Is anyone able to understand what I am doing wrong with my /download route?

***UPDATE: I changed the name of the /download/:fileid route to /test/:fileid and it worked. I then changed it BACK to /download/:fileid and it now works... does anyone have any idea what could of caused this?

1 Answers1

1

You have a few errors there, which can screw your debugging.

  1. You have misplaced your connection.end() statement which will be called immediately after connection.query(). You should move it inside of connection.query's callback.

  2. Using relative paths instead of abolute ones. Try changing './uploads/PFSk5x7bg.png' to __dirname + '/uploads/PFSk5x7bg.png'

  3. Not using res.end() in the request where necessary may confuse browser's representation of response of your software.

    if (error) { 
        res.end();
        throw error;
    }else if(results.length === 0){
        res.end();
        console.log("empty");
    }
    else{
        res.download(`./uploads/PFSk5x7bg.png`, 'PFSk5x7bg.png', (err) => {
            console.log(err);
        })
    }
    
CoderFF
  • 190
  • 1
  • 10