ASP.NET中的文件下载错误 - 来自Gridview的C#

时间:2015-12-29 09:23:08

标签: c# asp.net

请查看错误屏幕。我只想从gridview中的模板字段下载文件,我将文件保存在服务器目录和db。中的文件路径中。

任何使用此修复程序或适当的新解决方案

enter image description here

<asp:GridView ID="GridView1" runat="server" 
                onrowcommand="GridView1_RowCommand">
                <Columns>
                    <asp:TemplateField HeaderText="File">
                        <ItemTemplate>
                        <%--<asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("filepath") %>' runat="server" OnClick = "FilesDownload"></asp:LinkButton>
                    --%>
                            <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" 
                                Text='<%# Eval("Path") %>' CommandArgument='Eval("Path")'></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>



protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Download") 
            { Response.Clear(); Response.ContentType = "application/octectstream";
                Response.AppendHeader("content-dispositi­on", "filename=" + e.CommandArgument);

                Response.TransmitFile(Server.MapPath("~/­File") + "//" + e.CommandArgument);
                Response.End(); }
        }

1 个答案:

答案 0 :(得分:0)

您需要按照以下步骤操作: -

最后添加TemplateField,如下所示。

<asp:TemplateField>
    <ItemTemplate>
 <asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("file") %>' runat="server" OnClick="DownloadFile"></asp:LinkButton>
  </ItemTemplate>
</asp:TemplateField>

并且在Code-behind中执行以下操作: -

protected void DownloadFile(object sender, EventArgs e)
{
    try
    {
        string filePath = (sender as LinkButton).CommandArgument;
        System.Net.WebClient req = new System.Net.WebClient();
        HttpResponse response = HttpContext.Current.Response;
        response.Clear();
        response.ClearContent();
        response.ClearHeaders();
        response.Buffer = true;
        response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath("~/YourFolder/" + filePath) + "\"");
        byte[] data = req.DownloadData(Server.MapPath("~/YourFolder/" + filePath));
        response.BinaryWrite(data);
        response.End();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

参考链接: - http://www.aspsnippets.com/Articles/Download-Files-from-GridView-using-LinkButton-Click-Event-in-ASPNet-using-C-and-VBNet.aspx

希望有所帮助