Home >Web Front-end >JS Tutorial >How Do I Download Files from a Node.js Server Using Express?
Node.js' Express framework offers a convenient way to download files from a server to a client. To facilitate this, follow these steps:
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.
To enhance performance, use file streams to transmit data instead of reading the entire file synchronously. This approach minimizes potential delays or memory issues.
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. });
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); });
This solution includes:
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!