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

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

Linda Hamilton
Release: 2024-11-27 19:26:11
Original
559 people have browsed it

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

Downloading Files from Node.js Server Using Express

Problem:
How to download files from a file stored in the server, Downloading a file to local machine by accessing a page in Node.js server?

Solution:

Using the helper functions provided by Express.js can simplify this process:

app.get('/download', function(req, res){
  const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
  res.download(file); // Set disposition and send it.
});
Copy after login

Old solution :

In order for the browser to recognize the file name, you need to use other HTTP header to specify more information:

res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
Copy after login

You can also send MIME types, for example:

res.setHeader('Content-type', 'video/quicktime');
Copy after login

The following is a more detailed sample code:

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

Please Note that this example code uses a stream to read the file, which is the preferred asynchronous method in Node.js.

The above is the detailed content of How to Download Files from a Node.js Server Using Express.js?. 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