日期:2014-05-20 浏览次数:20930 次
public void Save()
{
if (System.IO.File.Exists(fileName))
{
FileInfo DownloadFile = new FileInfo(fileName);
System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.ClearHeaders(); System.Web.HttpContext.Current.Response.Buffer=false;
System.Web.HttpContext.Current.Response.Charset = "GB2312 "; System.Web.HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.UTF8;
System.Web.HttpContext.Current.Response.ContentType= "application/octet-stream ";
System.Web.HttpContext.Current.Response.AppendHeader( "Content-Disposition ", "attachment;filename= " +System.Web.HttpUtility.UrlEncode(DownloadFile.FullName,System.Text.Encoding.UTF8));
System.Web.HttpContext.Current.Response.AppendHeader( "Content-Length ",DownloadFile.Length.ToString());
// System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
// System.Web.HttpContext.Current.Response.Flush();
// System.Web.HttpContext.Current.Response.End();//原来的程序
byte[] tmpbyte=new byte[1024*8];
System.IO.FileStream fs=DownloadFile.OpenRead();
int count;
while((count=fs.Read(tmpbyte,0,tmpbyte.Length))> 0)
{
System.Web.HttpContext.Current.Response.BinaryWrite(tmpbyte); System.Web.HttpContext.Current.Response.Flush();
}
fs.Close();
System.Web.HttpContext.Current.Response.End();
}
}
------解决方案--------------------
xxx = Server.MapPath("~/xxx.txt");
if(File.Exists(xxx))
{
Response.Clear();
Response.ContentType= "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename="+ Path.GetFileName(xxx));
Response.WriteFile(xxx);
Response.End();
}
else
{
Response.Write("文件不存在");
}
另外,文件必须放在网站目录下,而不是放在网站目录外面
------解决方案--------------------
protected void Page_Load(object sender, EventArgs e)
{
FileDown("D:/MyPassWord.pmb");
}
private void FileDown(string strPath)
{
System.IO.FileInfo file = new System.IO.FileInfo(strPath);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.FullName, System.Text.Encoding.UTF8));
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();
Response.WriteFile(file.FullName);
Response.End();
}
else
{
ClientScript.RegisterStartupScript(GetType(), "", "<script language='javascript'>alert('文件不存在!');</script>");
}
}