解決一下問題:
1、火狐瀏覽器下載文件,中文變亂碼
2、IE瀏覽器下載文件,丟失文件擴展名或強制擴展名為".txt"
3、瀏覽器下載文件,文件名中的空格變成加號("+"),測試過程中chrome,firefox,ie均出現此問題
1 string fileFullName = @"D:\新建 Microsoft Word 文檔.docx"; //文件絕對路徑 2 string fileName = Path.GetFileName(fileFullName); 3 using (FileStream stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read, FileShare.Read)) 4 { 5 //指定塊大小 6 long chunkSize = 102400; 7 //建立一個100K的緩沖區 8 byte[] buffer = new byte[chunkSize]; 9 //未讀的字節數 10 long dataToRead = stream.Length; 11 12 //添加Http頭 13 string contentDisposition; 14 if (Request.Browser.Browser == "IE" && (Request.Browser.Version == "7.0" || Request.Browser.Version == "8.0")) 15 { 16 contentDisposition = "attachment;filename=" + Uri.EscapeDataString(fileName); 17 } 18 else if (Request.Browser.Browser == "Safari") 19 { 20 contentDisposition = "attachment;filename=" + fileName; 21 } 22 else 23 { 24 contentDisposition = "attachment;filename*=UTF-8''" + Uri.EscapeDataString(fileName); 25 } 26 //Response.AddHeader("Content-Disposition", contentDisposition); 27 28 HttpContext.Current.Response.ContentType = "application/octet-stream"; 29 HttpContext.Current.Response.AddHeader("Content-Disposition", contentDisposition); 30 HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString()); 31 32 while (dataToRead > 0 && HttpContext.Current.Response.IsClientConnected) 33 { 34 int length = stream.Read(buffer, 0, (int)chunkSize); 35 HttpContext.Current.Response.BinaryWrite(buffer); 36 HttpContext.Current.Response.Flush(); 37 HttpContext.Current.Response.Clear(); 38 39 dataToRead -= length; 40 } 41 HttpContext.Current.Response.Close(); 42 }