June 11, 2024

Express File Download Using res.download()

In your Express.js web application if you want to provide a functionality to download a file then that can be done by using response.download() method.

res.download() method in Express.js

Syntax of res.download() method is as given below-

res.download(path [, filename] [, options] [, fn])
  • path- Transfers the file at path as an "attachment". Typically, browsers will prompt the user for download.
  • Options- Optional parameters that can be passed. See the list of available options here- http://expressjs.com/en/5x/api.html#res.download
  • fn- Callback function that is called when the transfer is complete or when an error occurs. Takes one parameter err which encapsulates the error.

res.download() examples in Express.js and Node.js

This example shows how to download a .png image stored under /public/docs folder with in the project directory.

Downloading an image

var express = require('express');
var path = require('path');

var app = express();
const port = 3000;

app.get('/', function (req, res) {
    res.download(path.join(__dirname, "/public/docs/", "testimage.png"), (err) => {
        if (err) {
            console.log("Error : ", err);
            res.send("Problem downloading the file");
        }else{
            console.log('Document download done..');
        }
    });
});

//Server
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

Once you run the file and access URL http://localhost:3000/ browser should prompt you to download the file.

Downloading a PDF

You can download a pdf document too the same way.

var express = require('express');
var path = require('path');

var app = express();
const port = 3000;

app.get('/', function (req, res) {
    res.download(path.join(__dirname, "/public/docs/", "testdoc.pdf"), (err) => {
        if (err) {
            console.log("Error : ", err);
            res.send("Problem downloading the file");
        }else{
            console.log('Document download done..');
        }
    });
});

//Server
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

That's all for the topic Express File Download Using res.download(). If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment