分享一個在 ASP.NET MVC 中用 Ajax 觸發後端生成文件並下載的做法。
在 ASP.NET MVC 裡,Ajax 呼叫後臺 Action 只能拿到 JSON,沒辦法直接返回文件流——除非刷新頁面,但那樣就談不上 Ajax 了。因此思路是:先把生成的文件暫存到伺服器,再透過 JSON 把文件路徑返回前端,由前端發起真正的下載請求;下載完成後立刻刪除暫存檔。
以下以動態生成 Excel 為例(Excel 的具體生成過程不在本文重點,這裡直接省略)。
[HttpPost]
public JsonResult ExportExcel()
{
DataTable dt = DataService.GetData();
var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";
//將生成的文件保存到服務器的臨時目錄裡
string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);
using (var exportData = new MemoryStream())
{
//如何生成 Excel 這裡就不詳細說明了,我這裡對 Excel 的操作使用的是 NPOI
Utility.WriteDataTableToExcel(dt, ".xls", exportData);
FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
exportData.WriteTo(file);
file.Close();
}
var errorMessage = "you can return the errors in here!";
//返回生成後的文件名
return Json(new { fileName = fileName, errorMessage = "" });
}
[HttpGet]
[DeleteFileAttribute] //Action Filter:下載完後自動刪除文件,稍後解釋
public ActionResult Download(string file)
{
//到服務器臨時文件目錄下載相應的文件
string fullPath = Path.Combine(Server.MapPath("~/temp"), file);
//返回文件對象,這裡是 Excel,所以 content-type 用 application/vnd.ms-excel
return File(fullPath, "application/vnd.ms-excel", file);
}
public class DeleteFileAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.Flush();
//將當前 filter context 轉換成具體操作的文件並獲取文件路徑
string filePath = (filterContext.Result as FilePathResult).FileName;
//有文件路徑後就可以直接刪除相關文件了
System.IO.File.Delete(filePath);
}
}
//這裡我使用了 blockUI 做 loading 遮罩
$.blockUI({ message: '<h3>Please wait a moment...</h3>' });
$.ajax({
type: "POST",
url: '@Url.Action("ExportExcel", "YourController")', //調用相應的 controller/action
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (data) {
$.unblockUI();
//接收返回的文件路徑,此時文件已保存到服務器上
if (data.fileName != "") {
//透過 window.location.href 直接跳轉到 download action 觸發下載
window.location.href = "@Url.RouteUrl(new { Controller = "YourController", Action = "Download" })/?file=" + data.fileName;
}
});
整個流程可以概括為:Ajax 請求生成 → 後端落盤並回傳文件名 → 前端跳轉到下載地址 → Action Filter 在下載完成後刪除暫存文件。這樣既保留了 Ajax 的無刷新體驗,又達到了下載文件的目的。
實務上還建議補充兩點防護:一是暫存目錄要定期清理,避免使用者中途放棄下載造成垃圾文件堆積;二是 Download 傳入的 file 參數必須做白名單或路徑合法性校驗,否則存在路徑穿越的風險。