Open In App

How to handle file downloads in Express JS ?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

When using ExpressJS, handling file uploads involves receiving files from clients. On the other hand, file downloads refer to serving files to clients. For file uploads, we typically use libraries to handle the file processing. On the other hand, for file downloads, it is common to use NodeJS’s built-in module to read files and serve them to clients.

Handling File Downloads in ExpressJS:

  • Step 1: Install the necessary package in your application using the following command.
npm install express
  • Step 2: Create a route: First, you need to define a route in your ExpressJS application that will handle requests for downloading files.
  • Step 3: Specify the file: In this route, you specify which file the client is requesting to download. This could be any file on your server that you want to make available for download.
  • Step 4: Set response headers: Before sending the file to the client, you need to set certain headers in the response. These headers provide instructions to the client’s browser on handling the downloaded file. For example, you might set the Content-Disposition header to specify the filename and whether it should be displayed in the browser or downloaded directly.
  • Step 5: Send the file: Once you’ve set up the headers, you use the res.download() method provided by ExpressJS to send the file to the client. ExpressJS takes care of transferring the file and setting the appropriate headers automatically.
  • Step 6: Handle errors: It’s important to handle errors gracefully, such as when the requested file does not exist or cannot be accessed. You should provide appropriate error messages or responses to inform the client about what went wrong.

Example: Below is the example to handle file downloads in ExpressJS.

Javascript




// server.js
 
const express = require('express');
const app = express();
 
// Serve static files from the 'public' directory
app.use(express.static('public'));
 
// Route to handle file download
app.get('/download',
    (req, res) => {
        const fileName = 'myapp.txt';
        const filePath =
            __dirname + '/public/' + fileName;
 
        // Send the file as an attachment
        res.download(filePath, fileName);
    });
 
// Start the server
const port = 3000;
app.listen(port,
    () => {
        console.log(
            `Server is running
            on http://localhost:${port}`
        );
    });


Start the server using the following command.

node server.js

Output:

gfg18

Output


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads