using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//调用文件下载的方法
DownLoadFile("中文名.gif", "~/images/msg.gif");
}
}
///
/// 文件下载的方法
///
/// 下载时显示的文件名称(客户端保存的文件名)
/// 文件的路径
public void DownLoadFile(string fileName, string filePath)
{
string path = HttpContext.Current.Server.MapPath(filePath);//路径
if (File.Exists(path)) //如果文件存在
{
FileInfo fileInfo = new FileInfo(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
//加上HttpUtility.UrlEncode()方法,防止文件下载时,文件名乱码,(保存到磁盘上的文件名称应为“中文名.gif”)
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 = "application/octet-stream";
HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("gb2312");
HttpContext.Current.Response.WriteFile(fileInfo.FullName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}