Home >Web Front-end >JS Tutorial >How Can I Download Files from a NodeJS Server Using ExpressJS?

How Can I Download Files from a NodeJS Server Using ExpressJS?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 14:34:11584browse

How Can I Download Files from a NodeJS Server Using ExpressJS?

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.

  • File Name: res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV')
  • File Type: res.setHeader('Content-type', 'video/quicktime')

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!

Statement:
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