1 //filePath:完整的文件路径 2 //fileName:文件名 3 private void DownFile(string filePath, string fileName) 4 { 5 FileInfo fileInfo = new FileInfo(filePath); 6 string fileExt = fileInfo.Extension.Trim().ToLower(); 7 HttpContext.Current.Response.Clear(); 8 HttpContext.Current.Response.ClearContent(); 9 HttpContext.Current.Response.ClearHeaders(); 10 11 //显示在下面窗口的中文文件名 12 13 // HttpUtility.HtmlEncode : 将字符串转换为 HTML 编码的字符串。 14 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName)); 15 HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString()); 16 HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary"); 17 HttpContext.Current.Response.ContentType = checktype(HttpUtility.UrlEncodeUnicode(fileExt));//"application/octet-stream"; 18 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); 19 HttpContext.Current.Response.WriteFile(fileInfo.FullName); 20 HttpContext.Current.Response.Flush(); 21 HttpContext.Current.Response.End(); 22 } 23 24 25 26 27 28 public string checktype(string fileExt) 29 { 30 string ContentType; 31 switch (fileExt) 32 { 33 case ".asf": 34 ContentType = "video/x-ms-asf"; break; 35 case ".avi": 36 ContentType = "video/avi"; break; 37 case ".doc": 38 ContentType = "application/msword"; break; 39 case ".zip": 40 ContentType = "application/zip"; break; 41 case ".rar": 42 ContentType = "application/x-zip-compressed"; break; 43 case ".xls": 44 ContentType = "application/vnd.ms-excel"; break; 45 case ".gif": 46 ContentType = "image/gif"; break; 47 case ".jpg": 48 ContentType = "image/jpeg"; break; 49 case "jpeg": 50 ContentType = "image/jpeg"; break; 51 case ".wav": 52 ContentType = "audio/wav"; break; 53 case ".mp3": 54 ContentType = "audio/mpeg3"; break; 55 case ".mpg": 56 ContentType = "video/mpeg"; break; 57 case ".mepg": 58 ContentType = "video/mpeg"; break; 59 case ".rtf": 60 ContentType = "application/rtf"; break; 61 case ".html": 62 ContentType = "text/html"; break; 63 case ".htm": 64 ContentType = "text/html"; break; 65 case ".txt": 66 ContentType = "text/plain"; break; 67 default: 68 ContentType = "application/octet-stream"; 69 break; 70 } 71 return ContentType; 72 }