单击LinkBut​​ton事件无法下载文件

时间:2016-12-28 15:24:41

标签: c# asp.net linkbutton asplinkbutton

我在用户点击gridview中的链接按钮事件时尝试下载文件,但是没有下载该文件。

用户点击linkbutton事件时的代码:

protected void downloadLink_Click1(object sender, EventArgs e)
{
    LinkButton lnkbtn = sender as LinkButton;
    GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;


    string filename = lnkbtn.CommandArgument;

    byte[] mybuffer = Encoding.UTF8.GetBytes(filename);

    Response.Clear();
    Response.ClearHeaders();
    Response.ClearContent();
    //this puts the response to a page
    Response.ContentType = "application/" + "octet-stream";
    Response.AddHeader("Content-disposition", "attachment; filename=" + filename);
    Response.AddHeader("Content-Length", mybuffer.Length.ToString());

    Response.BinaryWrite(mybuffer);
    Response.Flush();
    Response.Close();
    Response.End();

}

1 个答案:

答案 0 :(得分:0)

当使用内存流写入文件时,此代码适用于我。我和我的代码之间的区别在于我有一个Content-Length标头。您可能需要获取文件大小并添加此标题。

 MemoryStream mybuffer= New MemoryStream(File.ReadAllBytes(filename));
 Response.Clear();
  Response.ClearHeaders();
  Response.ClearContent();
                //this puts the response to a page
  Response.ContentType = "application/" + "octet-stream";
  Response.AddHeader("Content-disposition", "attachment; filename=" + filename); 
  Response.AddHeader("Content-Length", mybuffer.Length.ToString());

  Response.BinaryWrite(mybuffer);
  Response.Flush();
  Response.Close();
   Response.End();