用页传值方式解决模态窗口的Response.WriteFile文件下载

    因为项目需要,使用了模态窗口,故在BasePage中的override void OnInit(EventArgs e)中加入如下内容.
            Response.Clear();
            Response.Buffer 
= true;
            Response.ExpiresAbsolute 
= System.DateTime.Now.AddSeconds(-1);
            Response.Expires 
= 0;
            Response.CacheControl 
= "no-cache";
            
string nocache = "<meta http-equiv=\"pragma\" content=\"no-cache\">\n";
            nocache 
+= "<meta http-equiv=\"cache-control\" content=\"no-cache, must-revalidate\">\n";
            nocache 
+= "<meta http-equiv=\"expires\" content=\"WED, 26 Feb 1997 08:21:57 GMT\">\n";
            Response.Write(nocache);
 可因为一个需求,需要在模态窗口中添加附件的下载功能,因为对附件个数的不确定,所以刚开始的解决方法是直接将附件路径写在<a href></a>里,单击直接下载,使用过程中遇到了问题,譬如,当文件是图片或者是TXT文件是,IE浏览器是直接在线打开的.而我要求是点击后提示是否保存或者打开(注:模态窗口禁用了右键,所以没有另存为).
      怎样才能让IE出现提示呢?我就想到了Response.WriteFile(),但是,因为我的是模态窗口,我去掉了页面缓存.这样就没办法实现了.废话不多说了,最后我的解决方法是利用页面传值方式(简单吧,就怕没想到),将文件路径和文件名传到另一个页面,然后用Request.QueryString获取值.
下面代码分别是附件页面和下载页面.
string slink ="<div><TABLE  border=0><TR><TD&nbsp附件名称</TD><TD>&nbsp附件说明</TD></TR>";
for(int j =0;j<dt.Rows.Count;j++)
            
{
                
string strpath = Server.UrlEncode(GlobalVar.UploadPath+ "/" +dt.Rows[j]["Filename"].ToString());
                
string strfilename = Server.UrlEncode(dt.Rows[j]["Filename"].ToString());
                
string strUrl = "FileDownLoad.aspx?pathname="+strpath + "&filename="+ strfilename;
                slink 
+= "<TR><TD><a href=\""+ strUrl +"\" target=\"_blank\")>"+ dt.Rows[j]["Filename"].ToString() +"</a>&nbsp&nbsp&nbsp&nbsp</TD><TD>"+dt.Rows[j]["Explain"].ToString()+"</TD></TR>";
            }
其中的dt 是附件表,GlobalVar.UploadPath是附件地址,Server.UrlEncode是为了中文附件名的传值.
FileDownLoad.aspx的.cs文件如下(FileDownLoad没有用BasePage的)
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 在此处放置用户代码以初始化页面
            string sfilePath = Request.QueryString["pathname"];
            
string sfilename = Request.QueryString["filename"];
            Response.Clear();
            Response.Charset 
= "utf-8";
            Response.Buffer
= true;
            
this.EnableViewState = false;
            Response.ContentEncoding 
= System.Text.Encoding.UTF8;
            Response.AppendHeader(
"Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(sfilename, System.Text.Encoding.UTF8)); 
            Response.WriteFile(sfilePath); 
            Response.Flush();
            Response.Close();
            Response.End();
        }
posted @ 2006-10-16 09:50  zjy  阅读(2632)  评论(10编辑  收藏  举报