【问题标题】:How to download html file on a click of button in asp.net?如何在asp.net中单击按钮下载html文件?
【发布时间】:2016-08-03 05:26:50
【问题描述】:

我正在 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目录下的下载文件夹中。

【问题讨论】:

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


    【解决方案1】:

    你有没有试过最后发送这个作为回应:

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

    【讨论】:

    • 它的工作真棒......我已经应用了但是对于知识库我可以知道什么是 application/octet-stream 和 Content-Disposition","attachment;文件名=abc.html...请告诉我
    • @BasantGera 在服务器和客户端之间的每个请求和响应中,都有 HTTP 标头,其中包含有关客户端浏览器、请求页面、服务器的信息,这里添加 application/octet-stream 作为内容类型以通知浏览器响应中存在流文件,所以如果你用text/html替换它,浏览器就会明白这是一个html文件。对于Content-Disposition","attachment; filename=abc.html,我们将文件名(abc.html)分配给http标头并将其作为附件发送(在浏览器中打开下载提示窗口)。
    • 你可以看到http头here如果对你有帮助,请检查答案已解决
    • 非常非常非常感谢。你太棒了...再次感谢 :->
    • 不客气!请将答案标记为已解决(like this img
    猜你喜欢
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多