我在网格视图中添加了一个下载链接。当我单击该文件时不会下载,但我可以在chrome中看到响应。点击查看chrome中的响应 我可以在chrome开发人员工具响应选项卡中看到文件数据,但下载代码不起作用。请帮忙。
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "downloadfile")
{
int rowId = Convert.ToInt32(e.CommandArgument);
int fileId = Convert.ToInt32(((Label)GridView1.Rows[rowId].FindControl("lblfileid")).Text);
string fileName;
string constr = ConfigurationManager.ConnectionStrings["DMS"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select FileName,FileData,FileContentType from Attachment where FileId=@fileId";
cmd.Parameters.AddWithValue("@fileId", fileId);
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
fileName = sdr["FileName"].ToString();
Response.ContentType = sdr["FileContentType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename="" + sdr["FileName"] + """);
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])sdr["FileData"]);
Response.Flush(); // Sends all currently buffered output to the client.
Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest();
//Response.TransmitFile(@"c:ip.txt");
}
con.Close();
}
}
}
catch (Exception ex)
{
}
Response.End();
}
<asp:GridView ID="GridView1" runat="server" DataKeyNames="FileId" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound" Width="426px" Height="169px" OnRowCommand="GridView1_RowCommand1" AutoGenerateColumns="false">
<Columns>
<asp:HyperLinkField DataTextField="FileName" InsertVisible="False" HeaderText="File Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("fileID") %>' runat="server" CommandName="downloadfile" OnClick="lnkDownload_Click" CausesValidation="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnlDwn" Text="Download file" runat="server" OnClick="lnlDwn_Click" CommandArgument='<%# Eval("fileID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblfileid" Text='<%# Bind("FileId") %>' runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="downloadfile" HeaderText="action" Text="Download" />
<asp:ButtonField CommandName="DeleteFile" HeaderText="action" Text="Delete File" />
</Columns>
</asp:GridView>
您需要启动整页回发,当您使用带有更新面板的下载时,您需要在更新面板中使用回发触发器,如下所示:
<asp:UpdatePanel runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="YourControlID" />
</Triggers>
</asp:UpdatePanel>