从ASP.NET MVC下载JQuery-AJAX请求中的excel文件

在我的ASP.NET MVC项目中,我使用ClosedXML生成了一个excel文件。

它适用于非ajax调用。 这是我的控制器动作方法

// Prepare the response Response.Clear(); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment;filename=\"" + reportHeader + ".xlsx\""); // Flush the workbook to the Response.OutputStream using (MemoryStream memoryStream = new MemoryStream()) { MyWorkBook.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); memoryStream.Close(); } Response.End(); 

现在我试图通过ajax请求来做到这一点。 但该文件不是从mvc控制器发送的。

 $.ajax({ url: url, type: "POST", data: fd, processData: false, contentType: false, beforeSend: function () { }, success: function (response) { }, error: function (request, status, error) { }, complete: function () { } }); 

我怎么能完成它? 先感谢您。

为什么不? ramiramilu使用window.locationiframe是正确的。 我做了同样的事情,但对于ASP.NET MVC3。

我建议使用返回FileContentResult控制器

关于FileContentResult MSDN的 FYI

最后我是怎么做的(控制器):

  [HttpPost] public HttpStatusCodeResult CreateExcel() { XLWorkbook wb = new XLWorkbook(XLEventTracking.Disabled); //create Excel //Generate information for excel file // ... if (wb != null) { Session["ExcelResult"] = wb; return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [HttpGet] public FileContentResult ExcelResult(string reportHeader) //it's your data passed to controller { byte[] fileBytes = GetExcel((XLWorkbook)Session["ExcelResult"]); return File(fileBytes, MediaTypeNames.Application.Octet, reportHeader + ".xlsx"); } 

在模型中(如果您愿意,可以删除静态,并使用实例调用它)

 public static byte[] GetExcel(XLWorkbook wb) { using (var ms = new MemoryStream()) { wb.SaveAs(ms); return ms.ToArray(); } } 

AJAX:

 $.ajax({ url: "@Url.Action("CreateExcel")", async: true, type: "POST", traditional: true, cache: false, statusCode: { 400: function () { alert("Sorry! We cannot process you request"); }, 200: function () { $("#fileHolder") .attr('src', '@Url.Action("ExcelResult")?reportHeader=' + reportHeader); } } }); 

顺便说一句,我删除了所有exception处理程序以简化代码,但我认为你可以自己完成。

您无法使用AJAX 直接下载文件,但您可以使用window.location与AJAX一起下载文件以下载文件。 我的意思是,如果您使用AJAX GET / POST,所有文件内容都将在浏览器的内存中,但无法保存到磁盘(由于JavaScript的限制)。

相反,您可以使用window.location指向URL,该URL又将获取文件并提示保存/打开提示。 或者,您可以使用隐藏的iFrame并使用将从中下载文件的URL设置iFramesrc属性。