javascript - 如何使用 jquery ajax 从 .net core 5 下载文件
问题描述
我有来自 .net core 5 WebApi 的文件响应,我需要通过 ajax 调用下载它。
当我直接从浏览器使用链接时,效果很好。但是如果我把它放在一个ajax调用中,下载的文件就会损坏。这是我的代码:
网络接口:
[HttpGet]
[ActionName("Download")]
public IActionResult GetShipmentCostFile([FromQuery] LogisticFilterModel filter)
{
var data = GetLogisticRecords(LSP, filter, out int _, 0, 0);
MemoryStream ms = data.ToExcel();
return File(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"export_{DateTime.Now:yyyyMMdd}.xlsx");
}
JS:
function DownloadExcel() {
let startDate = $("#billOfDateStart").val();
let endDate = $("#billOfDateEnd").val();
console.log(startDate, endDate);
var settings = {
"url": "https://localhost:51001/api/logisticdata/download?confirmed=false&date_of_billing_start=2021/3/10&date_of_billing_end=2021/4/1",
"method": "GET",
"timeout": 0,
"headers": {
"Authorization": "Bearer " + currentUser.idToken,
},
};
$.ajax(settings).done(function (response) {
console.log(response);
var blob = new Blob([response], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
})
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", "export.xlsx");
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
});
我无法使用直接链接下载,因为我需要在请求中添加身份验证标头。
如果有人可以提供帮助,非常感谢。
解决方案
推荐阅读
- php - 在while循环的每次迭代中添加一个计数到动态数组键
- latex - 如何有效地阻止具有字体颜色的文本?
- vba - 原项目太大时如何制作ACCDE文件
- rest - 使用 rest Api 将 solines 添加到 acumatica
- r - 如何在 gganimate 上添加交点?
- python-trio - 如何使用 trio 构建开始和结束同步调用?
- docker - 如何保存 docker 容器?
- list - 如何将项目添加到 Ansible 中的现有字典?
- javascript - 创建一个接受数字数组的函数
- javascript - 从 Bokeh Google Maps 包装器 (fitBounds()) 调用 Javascript 方法