我正在VS2015中开发一个程序。我动态创建了一个 abc.html 文件。现在我想要一个功能,当用户单击按钮时,Html 文件应该在浏览器中打开或保存。我该怎么做? 动态制作Html文件的代码如下:
客户端如下:
<asp:button ID="BtnGenrateHTML" runat="server" text=" Generate HTML " OnClick="btnAddnew_Click" />
后台代码如下
protected void TestThisHTML(object sender, EventArgs e)
{
string sFileFullName;
string sFilePath;
string sFileName;
string strHTMLGrid = "";
strHTMLGrid = strHTMLGrid + "Dear Customer,<BR><BR> Please provide below OTP to complete registration <BR><BR> ";
strHTMLGrid = strHTMLGrid + "<BR><BR> This OTP is valid for 15 minutes.";
strHTMLGrid = strHTMLGrid + "<BR><BR> With Best Regards - Indiefy";
strHTMLGrid = strHTMLGrid + "<BR><BR> Hi My name is Basant Gera";
sFilePath = Server.MapPath("");
sFileName = "abc.html";
sFileFullName = sFilePath + "\\" + sFileName;
if (!Directory.Exists(sFileFullName))
{
Directory.CreateDirectory(sFilePath);
}
// if it exist than to delete it.
if (System.IO.File.Exists(sFileFullName))
{
System.IO.File.Delete(sFileFullName);
}
// If it deleted than we need to create it again
FileStream fs = new FileStream(sFileFullName, FileMode.Create);
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine(strHTMLGrid);
}
fs.Close();
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "fncpopup();", true);
}
现在我的 abc.Html 文件工作正常... 现在我想单击按钮将此 Html 文件保存在浏览器上,并询问浏览器是否要打开它或将其保存到特定位置
<asp:button ID="BtnGenrateHTML" runat="server" text=" Generate HTML " OnClick="btnAddnew_Click" />
Html文件的保存位置---->我使用mappath.server将其保存在当前目录中。
如果可能的话,将其保存在我们PC目录的下载文件夹中。
最佳答案
您是否尝试过发送最后一条回复:
{...
....
fs.Close();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment; filename=abc.html");
Response.TransmitFile( sFileFullName );
Response.End();
....
}
关于javascript - 如何在asp.net中单击按钮下载html文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38735065/