protected void Button4_Click(object sender, EventArgs e)
{
string fileName = "aaa.txt";//客户端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路径
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
//----------------------------------------------------------
public void DownloadFile( System.Web.UI.Page WebForm,String FileNameWhenUserDownload ,String FileBody )
{
WebForm.Response.ClearHeaders();
WebForm.Response.Clear();
WebForm.Response.Expires = 0;
WebForm.Response.Buffer = true;
WebForm.Response.AddHeader("Accept-Language", "zh-tw");
//'文件名称
WebForm.Response.AddHeader("content-disposition", "attachment; filename='"+System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8)+"'");
WebForm.Response.ContentType = "Application/octet-stream";
//'文件内容
WebForm.Response.Write(FileBody);//-----------
WebForm.Response.End();
}
//上面这段代码是下载一个动态产生的文本文件,若这个文件已经存在于服务器端的实体路径,则可以通过下面的函数:
public void DownloadFileByFilePath( System.Web.UI.Page WebForm,String FileNameWhenUserDownload ,String FilePath )
{
WebForm.Response.ClearHeaders();
WebForm.Response.Clear();
WebForm.Response.Expires = 0;
WebForm.Response.Buffer = true;
WebForm.Response.AddHeader("Accept-Language", "zh-tw");
//文件名称
WebForm.Response.AddHeader("content-disposition", "attachment; filename='" + System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8) +"'" );
WebForm.Response.ContentType = "Application/octet-stream";
//文件内容
WebForm.Response.Write(System.IO.File.Rea}dAllBytes(FilePath));//---------
WebForm.Response.End();
}