C # File Download (applicable to various browsers ),

Source: Internet
Author: User

C # File Download (applicable to various browsers ),

1. cs code

1 public void DownFile (string filePath, string fileName) 2 {3 // filePath File path example:/File/record .xlsx 4 5 // fileName File name example: Record .xlsx (suffix required) 6 Encoding encoding; // declare Encoding 7 string outputFileName; // output name 8 Debug. assert (HttpContext. applicationInstance. request. userAgent! = Null, "HttpContext. ApplicationInstance. Request. UserAgent! = Null "); 9 string browser = HttpContext. applicationInstance. request. userAgent. toUpper (); 10 // Microsoft's browser and ie filter 11 if (browser. contains ("MS") & browser. contains ("IE") 12 {13 outputFileName = HttpUtility. urlEncode (filePath); 14 encoding = Encoding. default; 15} 16 // Firefox 17 else if (browser. contains ("FIREFOX") 18 {19 outputFileName = fileName; 20 encoding = Encoding. getEncoding ("GB2312"); 21} 22 else23 {24 outpu TFileName = HttpUtility. urlEncode (fileName); 25 encoding = Encoding. default; 26} 27 28 string absoluFilePath = Server. mapPath (filePath); // obtain the Upload File Path 29 FileStream fs = new FileStream (absoluFilePath, FileMode. open); 30 byte [] bytes = new byte [(int) fs. length]; 31 fs. read (bytes, 0, bytes. length); 32 fs. close (); // Close the stream and release resource 33 HttpContext. applicationInstance. response. clear (); 34 HttpContext. applicationInstance. Response. buffer = true; 35 HttpContext. applicationInstance. response. contentEncoding = encoding; 36 HttpContext. applicationInstance. response. addHeader ("Content-Disposition", string. format ("attachment; filename = {0}", string. isNullOrEmpty (outputFileName )? DateTime. now. toString ("yyyyMMddHHmmssfff"): outputFileName); 37 Response. binaryWrite (bytes); 38 Response. flush (); 39 HttpContext. applicationInstance. response. end (); 40}

2. html code

The front-end HTML should write a tag, for example, <a href = 'downfile' target = '_ blank'> File Download </a>

 

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.