我需要做的是在点击按钮上生成一个csv文件我有所有工作调用javascript使用ajax导出文件然后我想让它使浏览器下载新导出的文件。根据用户导出的数据,这些文件将具有不同的名称。
$('#ui_btn_ExportCsv').click(function (event) {
var formContainer = $("#infoForm");
$.ajax({
type: 'GET',
url: '/Report/ExportReport',
data: formContainer.serialize(),
//contentType: 'application/json; charset=utf-8',
//dataType: 'json',
success: function (returnValue) {
window.location = "/Report/Download?file='" + + "'";
}
});
});
在我的控制器中,我调用ExportReport操作并返回Json
[HttpGet]
public JsonResult ExportReport(ReportsViewModel reportsViewModel)
{
//doing the export here and generating the file out on the server....
return Json(new { success = true, reportExportFile = reportExportPath },JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Download(string file)
{
string fullPath = Path.Combine(Server.MapPath("~/Report Export"), file);
return File(fullPath, "application/vnd.ms-excel", file);
}
然后关于ExportReport的成功,我试图将文件发送回下载,但似乎无法让它工作。我认为这是因为ajax调用是异步调用,没有什么可以控制浏览器告诉它下载。任何帮助将不胜感激!
答案 0 :(得分:2)
您应该将文件名传递给window.location网址,并且不要使用单个撇号。
$('#ui_btn_ExportCsv').click(function (event) {
var formContainer = $("#infoForm");
$.ajax({
type: 'GET',
url: '/Report/ExportReport',
data: formContainer.serialize(),
//contentType: 'application/json; charset=utf-8',
//dataType: 'json',
success: function (returnValue) {
window.location = "/Report/Download?file=" + yourFileName;
}
});
});
我相信你可以从这里得到它:
returnValue.reportExportFile