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
Release: 2024-11-30 14:34:11
Original
523 people have browsed it

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

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

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

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!

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