从服务器下载 Excel 个文件并保存在客户端

Download Excel file from server and save on client

我有一个 JavaScript 应用程序和一个 API,它创建了一个 Excel 文件和 returns 一个包含以下内容的字节数组 headers:

Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Content-Disposition:attachment; filename=List.xlsx

当我进入 Excel 资源 API URL 时,系统提示我下载 Excel 文件。如果我这样做,它可以正常下载并在 Excel 中打开。一切都很好。

现在问题来了:

我不想在用户浏览器window中暴露APIURL,所以我的目标是:

我的是这样的:

它下载文件,但是当我尝试打开文件时,Excel 无法将其识别为有效的 Excel 文件。

// "data" is the contents from the server

var reader = new FileReader();
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
reader.readAsDataURL(blob);

reader.onloadend = function (e) {
    window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no', '_blank');
}

我成功了。我只需要将以下内容添加到我的 XMLHttpRequest 对象中:

responseType: 'arraybuffer'

但是在IE中不行,因为IE不能打开数据URI。甚至 IE11.

无论如何我发现 a great library called FileSaver.js 处理所有主要浏览器(包括 IE10+)的保存文件