文件下载 文件名乱码问题解决
.NET中可通过以下函数实现文件的下载:
/// <summary>
/// 下载文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名</param>
public static void DownloadFile(string filePath, string fileName)
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException();
}
FileInfo info = new FileInfo(filePath);
long fileSize = info.Length;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
// 指定文件大小
HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
HttpContext.Current.Response.WriteFile(filePath, 0, fileSize);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
HttpContext.Current.Response.Close();
}
/// 下载文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名</param>
public static void DownloadFile(string filePath, string fileName)
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException();
}
FileInfo info = new FileInfo(filePath);
long fileSize = info.Length;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
// 指定文件大小
HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
HttpContext.Current.Response.WriteFile(filePath, 0, fileSize);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
HttpContext.Current.Response.Close();
}
这里要注意
HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString()这句,如果直接在这里传入fileName在IE中下载的文件名会乱码。
posted on 2012-08-11 13:26 Ray_bihpgh20 阅读(399) 评论(0) 编辑 收藏 举报