我會做,長話短說:當用戶點擊 「下載」 按鈕,使用AJAX調用 處理頁面
異步。該頁面將生成您的Excel文檔 並將其存儲在一個臨時位置
當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不應該顯示,只能下載,所以你的用戶應該停留在下載頁面上。
感謝您的非常詳細的答案,我儘量不使用臨時文件,但總是有一些被遺忘。 –