我会做,长话短说:当用户点击 “下载” 按钮,使用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不应该显示,只能下载,所以你的用户应该停留在下载页面上。
感谢您的非常详细的答案,我尽量不使用临时文件,但总是有一些被遗忘。 –