如何下载绑定到gridview的文件

How to download a file bound to an gridview

本文关键字:gridview 文件 绑定 何下载 下载      更新时间:2023-09-26

我错过了一些简单的东西。

我正在生成一些二进制文件,我将它们绑定到GridView。

    FileDownloadGrid.DataSource = downloadList;
    FileDownloadGrid.DataBind();
网格中有趣的部分是这样编码的:
    <asp:TemplateField>
       <ItemTemplate>
         <asp:LinkButton ID="DownloadFile" runat="server" Text="Download" CommandName="DownloadFile1"
           CommandArgument='<%#Eval("FullName") +"|" + Eval("Name") %>'> 
         </asp:LinkButton>
       </ItemTemplate>
     </asp:TemplateField>

我正在尝试使用IFRAME Ajax方法下载文件。

function InitializeRequest(sender, args) {
  // Check to be sure this async postback is actually
  //   requesting the file download.
  if (sender._postBackSettings.sourceElement.id == "FileDownloadGrid") {
    // Create an IFRAME.
    var iframe = document.createElement("iframe");
    // Get the desired region from the dropdown.
    var fName = $get("CommandArgument").value;
    // Point the IFRAME to GenerateFile, with the
    //   desired region as a querystring argument.
    iframe.src = "Default2.aspx?fName=" + fName;
    // 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);
  }
}

从我能在网上找到的,我不能拿起客户端CommandArgument,我似乎不知道如何在脚本中获得'FullName'。

谁能给我指个正确的方向?我为一件应该很简单的事而烦恼。

感谢基因

咬牙切齿之后,我决定直接调用JavaScript函数。

javascript:

function DownloadFile(filename) {
    // Check to be sure this async postback is actually
    // Create an IFRAME.
    var iframe = document.createElement("iframe");
    // Point the IFRAME to GenerateFile, with the
    //   desired region as a querystring argument.
    iframe.src = "Default2.aspx?fileName=" + filename;
    // 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);
}

下面是为我工作的代码:

<asp:LinkButton ID="DownloadFile" runat="server" Text="Download"  
   onClientClick='<%# string.Format("DownloadFile('"{0}'");", Eval("FullName")) %>'></asp:LinkButton>

一个关键位似乎正在将'FullName'路径从'转换为/。

      string serverPath = toFileName.Replace("''", "/");

然后在default2.aspx.cs中我这样做:

protected void Page_Load(object sender, EventArgs e)
{
  string workPath = Request.QueryString["fileName"];
  string fullPath = workPath.Replace('/', '''');
  string fileName = Path.GetFileName(fullPath);
  string attachmentHeader = String.Format("attachment; filename={0}", fileName);
  Response.AppendHeader("content-disposition", attachmentHeader);
  Response.ContentType = "application/octet-stream";
  Response.WriteFile(fullPath);
  Response.End();
}

我相信有更好的方法来完成所有这些,但这是我通过hack想出的,我希望它能帮助到其他人。