通过iframe实现Ajax文件下载

减小字体 增大字体 作者:佚名  来源:本站整理  发布时间:2008-7-19 18:15:27

<html>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" />
<script language="javascript">
  // Get a PageRequestManager reference.
  var prm = Sys.WebForms.PageRequestManager.getInstance();
   // Hook the _initializeRequest event and add our own handler.
  prm.add_initializeRequest(InitializeRequest);
   function InitializeRequest(sender, args){
    // Check to be sure this async postback is actually
     //   requesting the file download.
    if (sender._postBackSettings.sourceElement.id == "DownloadFile")
    {
      // Create an IFRAME.
      var iframe = document.createElement("iframe");
       // Get the desired region from the dropdown.
      var region = $get("Region").value;
       // Point the IFRAME to GenerateFile, with the
      //   desired region as a querystring argument.
      iframe.src = "GenerateFile.aspx?region=" + region;
       // This makes the IFRAME invisible to the user.
      iframe.style.display = "none";
       // Add the IFRAME to the page.  This will trigger
      //   a request to GenerateFile now.
      document.body.appendChild(iframe);
     }
  }
</script>
<asp:UpdatePanel runat="server">
  <ContentTemplate>
    <asp:DropDownList runat="server" ID="Region">
      <asp:ListItem Value="N">North Region</asp:ListItem>
      <asp:ListItem Value="W">West Region</asp:ListItem>
      <asp:ListItem Value="SE">Southeast Region</asp:ListItem>
    </asp:DropDownList>
    <asp:Button runat="server" ID="DownloadFile" Text="Generate Report" />
  </ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

GenerateFile.aspx

protected void Page_Load(object sender, EventArgs e){
  string FileResponse;
  string Region = Request.QueryString["Region"];
   // Code here to fill FileResponse with the
   //  appropriate data based on the selected Region.
   Response.AddHeader("Content-disposition", "attachment; filename=report.csv");
  Response.ContentType = "application/octet-stream";
  Response.Write(FileResponse);
  Response.End();
}

[数据载入中...] [返回上一页] [打 印]