Open In App

How to implement file uploading and downloading with Express ?

Last Updated : 21 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

File uploading and downloading are important features of a web app. Here we are going to handle file upload using express-fileupload npm package, and the download is handled using res.download() function of the express. The express-fileupload is passed to the app as the middleware.

Approach: First, install express-fileupload module and then require it and pass it as middleware to the app as shown below:

const fileUpload = require('express-fileupload')
app.use(fileUpload())

Then in order to access the uploaded files inside POST request using:

req.files.<uploaded_file_name>

It provides some functions and values such as file name, mime type, data, and size. It provides an important mv() function which is used to save the uploaded file. It takes the upload path and an error handling function as parameters.

req.files.<uploaded_file_name>.mv(<upload_path>, function(err) {
  // statement(s)
})

The download is handled using res.download() function which takes two parameters: file path and error handling function.

res.download( <file_path>, function(err) {
  // statement(s)
})

Implementation of uploading and downloading:

Step 1: Create an app.js file, index.html file, and initialize the project using the following command:

npm init

Step 2: Install express and express-fileupload using the following command:

npm install express
npm install express-fileupload

Project Structure: The project structure would look like the following. Create an upload folder inside the project directory and also create a file named download_gfg.txt inside the project folder, which would be downloaded.

Project Structure

Step 3: Now let’s first code the index.html file. In it, we create two forms, the one which handles upload has action=’/upload’ and the one which handles download has action=’/download’.

index.html




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Files</title>
</head>
<body>
    <!-- Upload section-->
    <div>
        <h3>Upload Section</h3> <br>
        <!-- action to the /upload route-->
        <form action="/upload" 
              method="post"
              enctype="multipart/form-data">
            File to be uploaded: <input type="file" 
                                        name="uploadFile" 
                                        id=""
            <br><br>
            <button type="submit">Upload</button>
        </form>
        <br>
    </div>
  
    <!-- Download Section-->
    <div>
        <h3>Download Section</h3> <br>
        <!-- action to the /download route-->
        <form action="/download" method="get">
            <button type="submit">Download</button>
        </form>
    </div>
      
</body>
</html>


Step 4: Now we will code the app.js file. In it, we have created a POST route – ‘/upload’ to handle upload and GET route – ‘/download’ to handle download. For the GET request to the root of the app, we send the index.html file.

app.js




// Requiring express to handle routing
const express = require("express");
  
// The fileUpload npm package for handling
// file upload functionality
const fileUpload = require("express-fileupload");
  
// Creating app
const app = express();
  
// Passing fileUpload as a middleware
app.use(fileUpload());
  
// For handling the upload request
app.post("/upload", function (req, res) {
  
  // When a file has been uploaded
  if (req.files && Object.keys(req.files).length !== 0) {
    
    // Uploaded path
    const uploadedFile = req.files.uploadFile;
  
    // Logging uploading file
    console.log(uploadedFile);
  
    // Upload path
    const uploadPath = __dirname
        + "/uploads/" + uploadedFile.name;
  
    // To save the file using mv() function
    uploadedFile.mv(uploadPath, function (err) {
      if (err) {
        console.log(err);
        res.send("Failed !!");
      } else res.send("Successfully Uploaded !!");
    });
  } else res.send("No file uploaded !!");
});
  
// To handle the download file request
app.get("/download", function (req, res) {
  
  // The res.download() talking file path to be downloaded
  res.download(__dirname + "/download_gfg.txt", function (err) {
    if (err) {
      console.log(err);
    }
  });
});
  
// GET request to the root of the app
app.get("/", function (req, res) {
  
  // Sending index.html file as response to the client
  res.sendFile(__dirname + "/index.html");
});
  
// Makes app listen to port 3000
app.listen(3000, function (req, res) {
  console.log("Started listening to port 3000");
});


Step to run the application: Start the application using the following command.

node app.js

Output: Open the browser and go to http://localhost:3000/, you will see the following command:

output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads