Download Files from Express.js Servers with Complete Filename and Extension
In Node.js, serving a file for download is straightforward, but ensuring it has the correct name and file extension can be a bit trickier.
Old Approach:
When writing a file download route using Express.js, you'll need to explicitly set the Content-Disposition header to provide the file name and file extension. Additionally, you may want to include the Content-Length and Content-Type headers for better handling:
app.get('/download', function(req, res) { const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`; res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV'); res.write(fs.readFileSync(file, 'binary')); res.end(); });
Express.js Helper:
Express.js now includes a helper method called download that simplifies the file download process:
app.get('/download', function(req, res) { const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`; res.download(file); // Sets 'Content-Disposition' and sends the file });
Enhancements:
For more advanced functionality, you can utilize third-party libraries like path and mime to automatically determine the filename, file extension, and mime type:
const path = require('path'); const mime = require('mime'); app.get('/download', function(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); res.download(file); });
This approach ensures that your downloaded file always has the correct name and file extension, regardless of its location on the server.
The above is the detailed content of How to Download Files with Correct Filenames and Extensions from Express.js Servers?. For more information, please follow other related articles on the PHP Chinese website!