繁体   English   中英

链接按钮的点击事件无法下载CSV文件

[英]Download CSV file on click event of link button not working

下面的代码不起作用。 我想从链接按钮单击事件上的文件夹下载CSV文件。

protected void LinkButton1_Click(object sender, EventArgs e)
{
  string filePath = "~/Data/Book1.csv";
  System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(filePath));
  if (file.Exists)
  {
    WebClient req = new WebClient();
    HttpResponse response = HttpContext.Current.Response;
    //string filePath = "";
    response.Clear();
    response.ClearContent();
    response.ClearHeaders();
    response.Buffer = true;
    response.AddHeader("Content-Disposition", "attachment;filename=Filename.extension");
    byte[] data = req.DownloadData(Server.MapPath(filePath));
    response.BinaryWrite(data);
    response.End();   
  }
}

无需使用WebClient读取文件,您可以将其直接传输到客户端。 只要文件位于本地文件系统中,您就不需要使用Web请求来获取它,而是可以直接读取它。 这样效率更高。

protected void LinkButton1_Click(object sender, EventArgs e)
{
  string filePath = "~/Data/Book1.csv";
  System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(filePath));
  if (file.Exists)
  {
    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.ClearContent();
    response.ClearHeaders();
    response.AddHeader("Content-Disposition", "Attachment;Filename=" + file.Name);
    response.TransmitFile(file.FullName);
    response.Flush();
    response.End();   
  }
}

我还建议禁用缓冲区并在结束响应之前刷新内容。

正如@BobSwager指出的那样, Content-Disposition标头中存在一些问题。

暂无
暂无

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

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