下载文件 excel 询问 JQuery-AJAX 经过 ASP.NET MVC

在我的项目中 ASP.NET MVC 我生成了文件 excel, 使用
http://closedxml.codeplex.com/
.

他在电话不起作用很好 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 // {
}
}/;


我怎样才能做到这一点?
先感谢您。
已邀请:

帅驴

赞同来自:

为什么不?
拉米拉米尔是对的
window.location


iframe

.
我做了同样的事情 ASP.NET MVC3.

我建议使用返回的控制器
FileContentResult


FYI 关于
FileContentResult

https://msdn.microsoft.com/en- ... .aspx
最后,正如我所做的那样 /控制器/:


[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/;
}
}
}/;


BTW, 我删除了所有异常处理程序以简化代码,但我假设您可以自己执行此操作。

小明明

赞同来自:

你不能

DIRECTLY

使用。下载文件 AJAX, 但是您可以上传文件使用
window.location

结合 AJAX, 要加载文件。 我的意思是,如果你使用 AJAX GET/POST, 然后,文件的所有内容都将在浏览器内存中,但不能保存到磁盘中 /由于限制 JavaScript/.

相反,你可以使用
window.location

, 表示 URL, 反过来,这将提取文件并建议保存/打开邀请。 或者你可以使用隐藏
iFrame

并安装属性
src

iFrame 从 URL, 将从中下载文件。

要回复问题请先登录注册