2011-11-17 56 views
1

我有一個按鈕,在我的asp.net頁面做回發,創建一個Excel文件,清除響應流並寫入文件。然後用戶可以打開或保存文件用戶瀏覽器的標準對話框。隱藏加載圖像在asp.net回發文件下載

這個偉大的工程,我在此基礎上的代碼:

http://www.adventuresindevelopment.com/2009/05/27/how-to-export-data-to-excel-in-aspnet/

至於要創建的文件需要我創建了一個加載面板,只是一個隱藏的DIV相當長的時間,並將此當按鈕被點擊時可見。

但我的問題是如何在導出完成時隱藏這個DIV?我無法找到一種方法。我需要一些事件,如文件被完全傳輸到瀏覽器時觸發事件。

這可能嗎?最受讚賞的任何幫助。

感謝,

AJ

回答

1

我會做,長話短說:當用戶點擊 「下載」 按鈕,使用AJAX調用 處理頁面

  1. 異步。該頁面將生成您的Excel文檔 並將其存儲在一個臨時位置

  2. 當AJAX請求完成後,隱藏的「加載」面板,並 將用戶重定向到一個下載頁面。理想情況下,您應該將 重定向到打開文件的通用(.ashx)處理程序,設置一些頭文件, 將臨時文件傳輸給用戶,然後刪除文件 。

現在,在更多的細節:

在第一步中,你應該有,你看過一些臨時文件夾和寫入權限。使用系統臨時文件夾是好的,所以你可以使用Path.GetTempFileName。下面是什麼,你可以在一個ASHX處理程序寫一個例子:

public class Handler1 : IHttpHandler, IRequiresSessionState 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     string fName = Path.GetTempFileName(); 

     context.Response.ContentType = "text/plain"; 

     try 
     { 
      // Generate the Excel document 
      GenerateExcelInFile(fName); 

      // Store the file name in session for later use 
      context.Session["ExcelGeneratorFileName"] = fName; 

      // Send confirmation to the client 
      context.Response.Write("ok"); 
     } 
     catch (Exception e) 
     { 
      context.Response.Write("error"); 
      // TODO : Do some logging 
     } 

    } 

    // SNIP : IsReusable 
} 

之後,用自己喜歡的JS框架,請​​求處理程序,並測試返回的字符串。如果是「OK」,你叫兩部分處理:

public class Handler2 : IHttpHandler, IRequiresSessionState 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     context.Response.ContentType = "application/excel"; 

     // Make sure the browser will show a "save as" dialog to the user 
     context.Response.AddHeader("content-disposition", "attachment; filename=Export.pdf"); 

     string fName = context.Session["ExcelGeneratorFileName"] as String; 

     if (fName != null && File.Exists(fName)) 
     { 
      // Stream the excel file to the response 
      context.Response.WriteFile(fName); 

      // Remove the file 
      File.Delete(fName); 
     } 
    } 

    // SNIP : IsReusable 
} 

您可以在javascript只需使用window.location = url調用這個頁面。 content-disposition標題會告訴瀏覽器該URL不應該顯示,只能下載,所以你的用戶應該停留在下載頁面上。

+0

感謝您的非常詳細的答案,我儘量不使用臨時文件,但總是有一些被遺忘。 –