C file download instance code (for each browser)
- 2021-12-12 09:30:17
- OfStack
1. cs code
public void DownFile(string filePath ,string fileName )
{
// filePath File path For example: /File/ Record .xlsx
// fileName File name For example: Records .xlsx (Suffix oh)
Encoding encoding; // Declaration code
string outputFileName; // Output name
Debug.Assert(HttpContext.ApplicationInstance.Request.UserAgent != null, "HttpContext.ApplicationInstance.Request.UserAgent != null");
string browser = HttpContext.ApplicationInstance.Request.UserAgent.ToUpper();
// Microsoft's browser and ie Filter
if (browser.Contains("MS") && browser.Contains("IE"))
{
outputFileName = HttpUtility.UrlEncode(filePath);
encoding = Encoding.Default;
}
// Firefox
else if (browser.Contains("FIREFOX"))
{
outputFileName = fileName;
encoding = Encoding.GetEncoding("GB2312");
}
else
{
outputFileName = HttpUtility.UrlEncode(fileName);
encoding = Encoding.Default;
}
string absoluFilePath = Server.MapPath(filePath); // Get the upload file path
FileStream fs = new FileStream(absoluFilePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close(); // Close the flow and free the resource
HttpContext.ApplicationInstance.Response.Clear();
HttpContext.ApplicationInstance.Response.Buffer = true;
HttpContext.ApplicationInstance.Response.ContentEncoding = encoding;
HttpContext.ApplicationInstance.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", string.IsNullOrEmpty(outputFileName) ? DateTime.Now.ToString("yyyyMMddHHmmssfff") : outputFileName));
Response.BinaryWrite(bytes);
Response.Flush();
HttpContext.ApplicationInstance.Response.End();
}
2. html code
It is good to write an a tag on the front-end HTML: such as
<a href='DownFile' target='_blank'>文件下载</a>