解决一下问题:
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 }