9951 explained code solutions for 126 technologies


expressjsHow do I download a zip file using Express.js?


To download a zip file using Express.js, you will need to use the express.static middleware.

First, you'll need to create a route in the Express server that will serve the zip file:

// Serve zip file
app.get('/download', function(req, res){
  res.download('/path/to/zipfile.zip');
});

Then, you'll need to use the express.static middleware to make the zip file accessible to the client.

// Serve static files
app.use(express.static(__dirname + '/public'));

Finally, you can send an AJAX request from the client side to the route you created to trigger the download:

// Send AJAX request
$.ajax({
  url: '/download',
  type: 'GET',
  success: function(data) {
    console.log('Download successful!');
  }
});

The client will then receive the zip file, which can be opened and used as needed.

Code explanation

  1. Create a route in the Express server that will serve the zip file:
    // Serve zip file
    app.get('/download', function(req, res){
      res.download('/path/to/zipfile.zip');
    });
  2. Use the express.static middleware to make the zip file accessible to the client:
    // Serve static files
    app.use(express.static(__dirname + '/public'));
  3. Send an AJAX request from the client side to the route you created to trigger the download:
    // Send AJAX request
    $.ajax({
      url: '/download',
      type: 'GET',
      success: function(data) {
        console.log('Download successful!');
      }
    });

Helpful links

Edit this code on GitHub