2017-07-12 48 views
0

以下代碼段不起作用。我想從鏈接按鈕點擊事件的文件夾中下載一個CSV文件。在點擊鏈接按鈕不起作用的事件下載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(); 
    } 
} 
+0

'Response.AppendHeader(「Content-Disposition」,「Attachment; Filename =」+ file.Name +「」);' –

+0

您可以嘗試使用我發佈的代碼。 –

+0

「不工作」是什麼意思?你有例外嗎?文件沒有傳輸到客戶端嗎?你爲什麼使用'WebClient'來讀取文件? – Markus

回答

0

而不是通過使用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標題中存在一些問題。

相關問題