通过 Ajax 下载生成的 CSV 文件



我正在尝试通过ajax下载或至少打开生成的csv文件。我已经设法记录了输出,一切都很好。是否可以通过 ajax 执行此操作,或者我必须尝试其他方式?控制器

[HttpPost]
public FileResult GenerateEventLogsReport([FromBody]GenericReportDateViewModel Input)
{
    var report = eventLogsData.Report(Input.StartDate, Input.EndDate);
    var sb = new StringBuilder();
    foreach(var item in report)
    {
        sb.AppendLine(item.Id + "," + item.Identity + "," + item.Level + "," + item.Logger + "," + item.Message + "," + item.TimeStamp + "," + item.Action);
    }
    return File(new UTF8Encoding().GetBytes(sb.ToString()),"text/csv","EventLogs_"+ Input.StartDate +"_to_"+ Input.EndDate +".csv");
}

阿贾克斯

var event_form_data = {
    "StartDate": $("#eventStartDate").val(),
    "EndDate": $("#eventEndDate").val(),
};
$.ajax({
    url: "@Url.Action("GenerateEventLogsReport", @ViewContext.RouteData.Values["controller"].ToString())",
    method: "POST",
    data: JSON.stringify(event_form_data),
    contentType: "application/json",
    success: function (result) {
        console.log(result);
        window.open("data:application/csv", result, "_blank");
    },
    error: function (error) {
        console.log(error);
    }
});

简而言之,您需要创建一个锚点,将结果的对象 URL 分配给 href,然后对其调用click()。此外,$.ajax调用需要指定你期待 blob 响应,因为 jQuery 中的默认设置是将响应视为文本。归根结底是如下所示的代码:

$.ajax({
    url: "@Url.Action("GenerateEventLogsReport", @ViewContext.RouteData.Values["controller"].ToString())",
    method: "POST",
    xhrFields: {
        responseType: 'blob'
    },
    data: JSON.stringify(event_form_data),
    contentType: "application/json",
    success: function (result) {
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(result);
        a.href = url;
        a.download = 'report.csv';
        document.body.append(a);
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
    },
    error: function (error) {
        console.log(error);
    }
});

我还有一个工作代码笔来演示。

最新更新