Home > Web Front-end > JS Tutorial > How to Download Files with Correct Filenames and Extensions from Express.js Servers?

How to Download Files with Correct Filenames and Extensions from Express.js Servers?

DDD
Release: 2024-12-02 11:53:11
Original
317 people have browsed it

How to Download Files with Correct Filenames and Extensions from Express.js Servers?

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();
});
Copy after login

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
});
Copy after login

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);
});
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template