Home > Web Front-end > JS Tutorial > How Do I Download Files from a Node.js Server Using Express?

How Do I Download Files from a Node.js Server Using Express?

Barbara Streisand
Release: 2024-12-04 21:25:15
Original
785 people have browsed it

How Do I Download Files from a Node.js Server Using Express?

Downloading Files from a Node.js Server with Express

Node.js' Express framework offers a convenient way to download files from a server to a client. To facilitate this, follow these steps:

Setting Headers

When sending a file, it's crucial to set the correct HTTP headers to provide the client with essential information like the file name and type.

  • Content-disposition: Set this header to 'attachment; filename=' to specify the file name as seen by the client.
  • Content-type: Indicate the type of file being downloaded, such as 'video/quicktime'.

Asynchronous File Streaming

To enhance performance, use file streams to transmit data instead of reading the entire file synchronously. This approach minimizes potential delays or memory issues.

Improved Solution

Express now includes a built-in function for file downloads:

app.get('/download', function(req, res) {
  const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
  res.download(file); // Sets the appropriate headers and streams the file.
});
Copy after login

Legacy Solution

Prior to Express' built-in download feature, the following code provides a more comprehensive file download solution:

var path = require('path');
var mime = require('mime');
var fs = require('fs');

app.get('/download', function(req, res) {

  var file = __dirname + '/upload-folder/dramaticpenguin.MOV';

  var filename = path.basename(file);
  var mimetype = mime.getType(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);
});
Copy after login

This solution includes:

  • File and file name extraction using path.basename.
  • Content type determination using node-mime.
  • Efficient file streaming with fs.createReadStream.

By following these techniques, you can effectively download files from your Node.js server via Express, ensuring clients correctly receive and recognize the downloaded content.

The above is the detailed content of How Do I Download Files from a Node.js Server Using Express?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template