Implementation of Asp.net File Download

Source: Internet
Author: User

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.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.