"Original: Http://www.jb51.net/article/89958.htm"
When the HTTP implementation file is downloaded, the client (browser) receives the file data based on the response header as long as the relevant response header is set on the server and the file data is transferred using binary. In node. js, when the response header is set, “.pipe()” Response a simple file download server can be implemented by reading the file stream and then using the method to transfer to the response object.
1. File Download Introduction
HTTP is based on the request header and the response header to achieve state interaction, when the server is properly responding to the state, and the client first resolves the response header, and based on the response header to receive and display the data (response body). For file downloads, the implementation process is as follows:
1. Client initiated file resource request
2. The server finds the corresponding file, and sets the " Content-Type ", " Content-Disposition " and other response headers, respectively, to indicate the file "MIME" type and file description
3. client resolves and receives file data based on response headers returned by the server
Response headers that need to be set
When setting up a file to download the response header, it is important to set the following two response headers in addition to the usual HTTP response headers:
?
| 12 |
Content-Type: application/octet-streamContent-Disposition: attachment; filename=MyFileName.ext |
In the settings above, " Content-Type: application/octet-stream " tells the browser that this is a binary file, " Content-Disposition " tells the browser that this is an attachment that needs to be downloaded and tells the browser the default file name. If you do not add a Content-Disposition response header, the browser may download or display the contents of the file, and different browsers will handle it differently.
Implementing HTTP File Downloads