Analysis on Node. js to Download HTTP File

  • 2021-07-09 06:45:24
  • OfStack

Preface

When HTTP realizes file download, it is only necessary to set the relevant response header in the server and transfer the file data in binary system, while the client (browser) will receive the file data according to the response header. In Node. js, after setting the response header, read the file stream and then use “.pipe()” Method to connect the flow to the response object Response You can realize a simple file download server.

1. Introduction to file download

HTTP realizes state interaction based on request header and response header. After obtaining the correct response state of the server, the client will first parse the response header and receive and display data (response body) according to the response header. For file download, the implementation process is as follows:

1. Client initiates file resource request

2. The server finds the corresponding file and sets " Content-Type "," Content-Disposition ", which is used to indicate the" MIME "type of the file and the file description, respectively

3. The client parses and receives the file data according to the response header returned by the server

Response header that needs to be set

When setting the file download response header, in addition to the commonly used HTTP response header, it is more important to set the following two response headers:


Content-Type: application/octet-stream
Content-Disposition: attachment; filename=MyFileName.ext

In the above settings, " Content-Type: application/octet-stream "Tell the browser this is a binary file," Content-Disposition "Tell the browser that this is an attachment that needs to be downloaded and tell the browser the default file name. If you do not add it" Content-Disposition "Response header, browsers may download or display file contents, and different browsers handle them differently.

2. Implementation of Node. js file download server

Next, we implement a simple file download server based on Express framework, which mainly includes two functions: browsing server files and downloading files.

2.1 Add Routes

After creating the Express application, add the following two routes:


router.get('/files', function(req, res, next) {
 //  Display server files  
});
router.get('/file/:fileName', function(req, res, next) {
 //  Implement file download  
});

The two routes added above are used to display server files and download files.

2.2 Displaying Server Files

To realize the display of server files, you should pass " fs "Module reads file directories and performs file/directory checks, etc. You also need to use the" path "module to process file paths. First, introduce these two modules:


const fs = require('fs');
const path = require('path');

The display server file implementation code is as follows:


router.get('/files', function(req, res, next) {
 //  Display server files  
 //  File directory 
 var filePath = path.join(__dirname, './');
 fs.readdir(filePath, function(err, results){
  if(err) throw err;
  if(results.length>0) {
   var files = [];
   results.forEach(function(file){
   if(fs.statSync(path.join(filePath, file)).isFile()){
     files.push(file);
   }
   })
   res.render('files', {files:files});
  } else {
   res.end(' There are no files in the current directory ');
  }
 });
});

In the above code, after reading the directory, pass the view file " files.ejs "Displays a list of downloadable files. The code is as follows:


<!DOCTYPE html>
<html>
 <head>
  <title> Download file selection </title>
 </head>
 <body>
  <h1> Please select the download file: </h1>
  <% if(files.length>0) {%>
  <ul>
   <% files.forEach(function(file){ %>
   <li>
    <a href="/file/<%- file %>" target="_blank"><%- file %></a>
   </li>
   <%})%>
  </ul>
  <%} else {%>
  <p> There are no downloadable files … </p>
  <%}%>
 </body>
</html>

2.3 Implement file download

When downloading files, you can read the files to 1 " Buffer "In, pass again" Response0 Or " res.end()” Method to send file data, or it can be based on the stream (" Stream ") to send file data. Use" Stream "When implementing file downloads, you can use the" fs.createReadStream()” Method creates a readable stream, and the response object Response Is a writable stream. In this way, you only need to pass ”.pipe()” Method to transfer the file flow to the Response Response flow.

The file download implementation code is as follows:


router.get('/file/:fileName', function(req, res, next) {
 //  Implement file download  
 var fileName = req.params.fileName;
 var filePath = path.join(__dirname, fileName);
 var stats = fs.statSync(filePath); 
 if(stats.isFile()){
  res.set({
   'Content-Type': 'application/octet-stream',
   'Content-Disposition': 'attachment; filename='+fileName,
   'Content-Length': stats.size
  });
  fs.createReadStream(filePath).pipe(res);
 } else {
  res.end(404);
 }
});

Summarize

The above is the use of Node. js to achieve HTTP file download of all the content, I hope you learn Node. js help.


Related articles: