您的位置:首页 > 其它

Response.AddHeader实现下载_解决下载界面中文文件名乱码问题

2016-02-29 12:39 811 查看
//filePath:完整的文件路径
//fileName:文件名
private void DownFile(string filePath, string fileName)
{
FileInfo fileInfo = new FileInfo(filePath);
string fileExt = fileInfo.Extension.Trim().ToLower();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();

//显示在下面窗口的中文文件名

// HttpUtility.HtmlEncode : 将字符串转换为 HTML 编码的字符串。
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
HttpContext.Current.Response.ContentType = checktype(HttpUtility.UrlEncodeUnicode(fileExt));//"application/octet-stream";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
HttpContext.Current.Response.WriteFile(fileInfo.FullName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}

public string checktype(string fileExt)
{
string ContentType;
switch (fileExt)
{
case ".asf":
ContentType = "video/x-ms-asf"; break;
case ".avi":
ContentType = "video/avi"; break;
case ".doc":
ContentType = "application/msword"; break;
case ".zip":
ContentType = "application/zip"; break;
case ".rar":
ContentType = "application/x-zip-compressed"; break;
case ".xls":
ContentType = "application/vnd.ms-excel"; break;
case ".gif":
ContentType = "image/gif"; break;
case ".jpg":
ContentType = "image/jpeg"; break;
case "jpeg":
ContentType = "image/jpeg"; break;
case ".wav":
ContentType = "audio/wav"; break;
case ".mp3":
ContentType = "audio/mpeg3"; break;
case ".mpg":
ContentType = "video/mpeg"; break;
case ".mepg":
ContentType = "video/mpeg"; break;
case ".rtf":
ContentType = "application/rtf"; break;
case ".html":
ContentType = "text/html"; break;
case ".htm":
ContentType = "text/html"; break;
case ".txt":
ContentType = "text/plain"; break;
default:
ContentType = "application/octet-stream";
break;
}
return ContentType;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: