简体   繁体   English

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

[英]Can't download file on LinkButton event clicked

I am trying to download file when user clicks link button event from gridview, but the file is not downloaded. 当用户单击gridview中的链接按钮事件时,我试图下载文件,但未下载文件。

The code i have when user clicks linkbutton event: 用户单击链接按钮事件时我拥有的代码:

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();

} }

This code works for me when using aa memory stream to write the file. 当使用内存流写入文件时,此代码对我有用。 The difference between my code and yours is that I have a Content-Length header. 我的代码和你的代码之间的区别在于,我有一个Content-Length标头。 You may have to get your file size and add this header. 您可能必须获取文件大小并添加此标头。

 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM