Objective
HTTP implementation file download, as long as the server set up the relevant response header, and use binary transfer file data, and the client (browser) will receive file data based on the response header. In Node.js, after setting the response header, read the file stream, and then use the “.pipe()”
method to transfer to the response object Response
can implement a simple file download server.
1. File Download Introduction
HTTP is based on the request header and the response header implementation State interaction, after getting the server to respond correctly, and the client will first resolve the response header, and according to the response header to receive and display data (response body). For file downloads, the implementation process is as follows:
1. Client initiated file resource request
2. The server looks for the corresponding file and sets the Content-Type
Content-Disposition
response headers such as "," to represent the "MIME" type of the file and the file description
3. Clients parse and receive file data based on the response headers returned by the server
Response headers that need to be set
When setting up a file download response header, in addition to the common HTTP response headers, it is important to set the following two response headers:
Content-type:application/octet-stream
content-disposition:attachment; filename=myfilename.ext
In the above setting, " Content-Type: application/octet-stream
tell the browser that 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 the Content-Disposition
response header, the browser may download or display the contents of the file, and different browsers will handle it differently.
2. node.js File Download Server implementation
Next we implement a simple file download server based on the Express framework, which mainly includes two functions: server file browsing , file downloading .
2.1 Adding routes
After creating the Express application, add the following two routes:
Router.get ('/files ', function (req, res, next) {
//display server file
});
Router.get ('/file/:filename ', function (req, res, next) {
//implementation file download
});
The two routes added above are used for: displaying server files, implementing file downloads, respectively.
2.2 Displaying server files
To implement the display of server files, through the " fs
" module to read the file directory and file/directory check and so on. You also need to use the "path" module to process the file path. First, the two modules are introduced:
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 file
//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 (' No files in current directory ');}});
In the code above, a list of downloadable files is displayed through the view file "" After reading the directory files.ejs
. The code is as follows:
2.3 Implementation File Download
When implementing a file download, you can read the file to a " Buffer
", then send the file data through the " res.send()”
or" method, or res.end()”
you can Stream
implement the sending of the file data based on the stream (""). When you use the Stream
implement file download, you can use the fs.createReadStream()”
method to create a readable stream, and the response object Response
is a writable stream. In this way, you only need to ”.pipe()”
transfer the file to Response
the response stream by means of a method.
The file download implementation code is as follows:
Router.get ('/file/:filename ', function (req, res, next) {
//implementation 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 the HTTP file download all the content, I hope to learn node.js help.