javascript - 如何在asp.net中单击按钮下载html文件?

标签 javascript c# html asp.net internet-explorer-11

我正在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/

相关文章:

html - Twitter Bootstrap 中同样大的列

javascript - 以 Angular 获取选中的复选框

c# - 打印缩放我的 WPF-GroupBox

c# - 使用 Azure 或 Microsoft Identity 中的角色进行授权

c# - 如何将图片保存到sqlite数据库

php - codeigniter 只能加载 index(),不能加载任何其他方法

javascript - 使用外部按钮处理表单的提交事件

javascript - 未捕获的类型错误 : Cannot read property 'map' of undefined in reactjs even when using it on array

javascript - 使用 onscroll 动态更改 div 的高度不起作用

javascript - 当光标悬停在图像上时显示文本