Downloading Files from NodeJS Server Using Express
When accessing a webpage on a NodeJS server, you may encounter the need to download files stored on the server. This article will guide you through the process of downloading files using the ExpressJS framework.
ExpressJS File Download
To initiate a file download, use the res.download() method provided by ExpressJS. This method automatically sets the necessary HTTP headers for file attachment and disposition.
To demonstrate:
app.get('/download', (req, res) => { res.download(`${__dirname}/upload-folder/dramaticpenguin.MOV`); });
Including File Name and Type
By default, downloaded files are named "download." To specify a custom file name and type, you need to set additional HTTP headers.
Comprehensive Implementation
Here's a more robust implementation using the mime library to determine the file's mime-type dynamically:
const path = require('path'); const mime = require('mime'); const fs = require('fs'); app.get('/download', (req, res) => { const file = __dirname + '/upload-folder/dramaticpenguin.MOV'; const filename = path.basename(file); const mimetype = mime.getType(file); res.setHeader('Content-disposition', `attachment; filename=${filename}`); res.setHeader('Content-type', mimetype); const filestream = fs.createReadStream(file); filestream.pipe(res); });
Using res.write()
If you prefer the res.write() approach, set the Content-Disposition and Content-Length headers first:
res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV'); res.setHeader('Content-Length', file.length); res.write(file, 'binary');
Remember to consistently use a readStream for file transmission rather than synchronous methods for optimal performance.
The above is the detailed content of How Can I Download Files from a NodeJS Server Using ExpressJS?. For more information, please follow other related articles on the PHP Chinese website!