簡體   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