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>