我正在尝试使用gridview的linkbutton从数据库下载文件,但是没有任何事情发生在它给我一个错误,也没有下载的文件。 这是我的实体:
我的数据库中有3个coulmns-SaleID& SaleFilename(此coulmn存储文件及其名称),SaleName(此列以字节存储相同的文件)
这是由.aspx代码:
<asp:TemplateField HeaderText="SaleName" SortExpression="SaleName">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Bind("SaleFileName") %>' Text='<%# Bind("SaleName") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
这是我的代码背后文件:
protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
// make sure fileName contains only file name like 'test.pdf'
string fileName = Convert.ToString(e.CommandArgument);
// make sure filePath contains file path like 'Uploads/Scheme/test.pdf'
string filePath = e.CommandArgument.ToString();
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
// SqlConnection con = new SqlConnection(connectionString);
byte[] bytes;
//string ContentType;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select SaleFileName from Sales";
cmd.Parameters.AddWithValue("@SaleFileName", SaleFileName );
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["SaleFileName"];
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
// Read the original file from disk
FileStream myFileStream = new FileStream( filePath ,FileMode.Open);
long FileSize = myFileStream.Length;
byte[] Buffer = new byte[Convert.ToInt32(FileSize)];
myFileStream.Read(Buffer, 0, Convert.ToInt32(FileSize));
myFileStream.Close();
// // Tell the browse stuff about the file
Response.AddHeader("Content-Length", bytes.ToString());
//Response.AddHeader("Content-Disposition", "inline; filename=" & fileName.Replace(" ", "_"));
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
Response.TransmitFile(fileName);
Response.ContentType = "application/octet-stream";
// Send the data to the browser
Response.BinaryWrite(Buffer);
Response.End();
}
}
当我们点击链接按钮下载文件时,网页没有给我任何回复,我是C#的新手,任何人都可以告诉我我在哪里犯了一个错误,这将是一个很大的帮助。