首先,我們新建一個模態窗口,在模態窗口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();
}
}