Skip to content

Download a file from NodeJS Server using ExpressJS

Last updated on November 21, 2022

In this tutorial, you will learn how to download files from your NodeJS server from your express js application. As your application is built using the ExpressJS framework you don’t have to play around with HTTP headers to allow downloads from your Node server. Express provides a Helper function called res.download(path [, filename] [, fn]); It transfers the file to path as an “attachment”. Using this function you can easily allow file downloads from your application.

Download a file from NodeJS Server using ExpressJS

This function, transfers the file at path as an "attachment". Typically, browsers will prompt the user for download. By default, the Content-Disposition header "filename=" parameter is path (this typically appears in the browser dialog). Override this default with the filename parameter.

When an error occurs or transfer is complete, the method calls the optional callback function fn. This method uses res.sendFile() to transfer the file.

Script to Download a file

Step 1: Create a package.json file and install dependencies.

$ mkdir expressjs-download
$ cd expressjs-download
$ npm init --yes
$ npm i -S express

Step 2: create a file called index.js in root expressjs-download/index.js of project. And create a express server with route, it should accept file name in the URL.

const express = require('express'); // import express js library
const app = express(); //create express js instance 
const path = require('path');
 
// define a route to download a file 
app.get('/download/:file(*)',(req, res) => {
  var file = req.params.file;
  var fileLocation = path.join('./uploads',file);
  console.log(fileLocation);
  res.download(fileLocation, file); 
});
 
app.listen(8000,() => {
  console.log(`application is running at: http://localhost:8000`);
});

Step 3: Run the application by issuing node index.js command from your terminal, you should be able to see the output "application is running at: http://localhost:8000" in your console and if you head over to the browser with http://localhost:8000/download/{filename}, you will get download prompt.

Here {filename} = name of the file including extension ( it will look for the file in expressjs-download/uploads directory)

Other resources

Getting Started with Express.js
Content-Disposition
How to serve static files with Express
File uploads in express js 4

0 0 votes
Article Rating
Subscribe
Notify of
guest

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments