2016-08-03 48 views
1

我正在开发VS2015中的程序。我已经动态创建了一个abc.html文件。现在我想要一个功能,当用户点击Html文件应该打开或保存在浏览器中的按钮。我该怎么做? 代码,使HTML文件动态如下:如何在asp.net中单击按钮下载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目录的下载文件夹中。

回答

1

您是否尝试过在响应发送此最后:

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

其工作真棒......我已经申请它不过对于知识库我可知道什么是应用程序/八位字节流和内容处置“”附件;文件名= abc.html ...请让我知道 –

+0

@BasantGera在服务器和客户端之间的每个请求和响应中都有HTTP标头,其中包含有关客户端浏览器,请求页面,服务器的信息 在这里,添加'application/octet-stream“作为内容类型来通知浏览器在响应中存在流文件,所以如果你用'text/html'替换它,浏览器就会明白这是一个html文件。 对于“Content-Disposition”,“attachment; filename = abc.html',我们将分配给http头文件名(abc.html)并将其作为附件发送(在浏览器中打开下载提示窗口)。 –

+0

你可以看到关于HTTP标头[这里](http://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039) 请检查答案已解决如果有帮助 –

相关问题