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

时间:2016-08-03 05:26:50

标签: 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文件的位置----&gt;我已使用mappath.server将其保存在当前目录中。

如果可能,请将其保存在我们的PC目录中的下载文件夹中。

1 个答案:

答案 0 :(得分:1)

你是否尝试过最后一次回复:

{...
    ....
    fs.Close();
    Response.ContentType = "application/octet-stream";
    Response.AppendHeader("Content-Disposition","attachment; filename=abc.html");
    Response.TransmitFile( sFileFullName );
    Response.End();
    ....
}