asp.net模態窗口下載文件解決方案

思路,在模態窗口頁面放一個影藏的iframe。 此處的iframe只是爲了觸發DownLoad.aspx頁面的page_load事件,完全可以用超鏈接等其它形式。
首先,我們新建一個模態窗口,在模態窗口a.aspx
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <base target="_self"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <center>
                    <asp:LinkButton ID="ibDownLoad" runat="server" onclick="ibDownLoad_Click">點擊這裏下載文件</asp:LinkButton>
    </center>
    <iframe id="download" runat="server" style="display:none;"></iframe>
    </form>
</body>
</html>



後臺代碼:

protected void ibDownLoad_Click(object sender, EventArgs e)
        {
            string filePath = Server.MapPath("\\PDF\\a.txt");
            download.Attributes["src"] = "DownLoad.aspx?filePath=" + filePath;
         }

處理文件下載頁面DownLoad.aspx,頁面代碼不寫,在後臺代碼寫:
protected void Page_Load(object sender, EventArgs e)
        {
            string filePath = Request.QueryString["filePath"];
            //string filePath = Server.MapPath("\\PDF\\a.txt");
            if (File.Exists(filePath))
            {
                FileInfo file = new FileInfo(filePath);
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解決中文亂碼
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解決中文文件名亂碼
               // Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                Response.AddHeader("Content-length", file.Length.ToString());
                Response.ContentType = "appliction/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章