A simple method is to directly write the server path of the server file to a linkbutton or hyperlink URL for the browser to complete the download. however, this is not flexible enough. You can only write every link during page_load, and directly use the plaintext public file path, greatly reducing the security.
Here we use a file transfer method based on the response object. The modification method is also based on the HTTP protocol.
You can write the following code in the corresponding function of a button:
Code
1 string filepath; // the path of the Server File.
2 string filename; // download the file name displayed.
3 if (system. Io. file. exists (filepath ))
4 {
5 // encoding to prevent garbled characters.
6 This. response. appendheader ("content-disposition", String. format ("attachment; filename = \" {0} \ ";", httputility. urlencode (filename, system. text. encoding. utf8 )));
7
8 response. contenttype = "application/octet-stream ";
9
10 response. addheader ("Content-Length", new system. Io. fileinfo (filepath). length. tostring ());
11
12 response. transmitfile (filepath );
13
14 This. response. End ();
15
16}
Of course, you can also use the Download Page Method to write the above Code to the page_load method of a page, and call response. Redirect in the corresponding method of the button to access the download page.