dpolicastro
dpolicastro

Reputation: 1519

Node.js - Serve file to be downloaded directly from browser without html

I would like to know if its possible to download a file directly from the browser on a GET request.

Let me explain:

I have a node.js API that I'm using to serve some files, and what I want is to directly download them when I make a get request to the resource from my browser. If its possible, what do I have to send? The full binary, pipe the response...? It's a bit confusing to me.

The code looks like this:

server.js

app.get('/document', async (req, res) => {
    const { filename } = req.query;

    const filepath = `${os.tmpdir()}/${filename}`
    try {
        var file = fs.readFileSync(filepath);
        return res.status(200).send({ msg: 'File read successfully', file: file })
    } catch (err) {
        return res.send({ msg: 'Problem reading file.', err: err.toString() })
    }

})

Upvotes: 0

Views: 1366

Answers (1)

dpolicastro
dpolicastro

Reputation: 1519

Found two ways to solve the problem;

1.Using res.download method from express

try {
    return res.download(filepath [, filename])
} catch (err) {
    return res.send({ err: 'Problem reading file.', msg: err.toString() })
}
  1. Sending the binaries and a special header
try {
        var file = fs.readFileSync(filepath);
        res.setHeader('Content-disposition', `attachment; filename=${filename}`);
        return res.status(200).send(file)
    } catch (err) {
        return res.send({ err: 'Problem reading file.', msg: err.toString() })
    }

Upvotes: 1

Related Questions