我需要使用 JavaScript 强制下载文件。我正在使用 Angular 和 reangular 与 API 进行通信。我现在正在处理来自 API 的文件下载操作...API 返回该文件的原始字节和这些 header :
Content-Disposition:attachment; filename="thefile"
Content-Length:2753
所以我有原始字节,但我不知道如何处理它以将该文件下载到客户端...你能为我提供这个问题的一些解决方案吗?如何处理从服务器返回的响应以在客户端浏览器“另存为”对话框中打开?
编辑: 服务器不会向我发送文件的内容类型...此外,在调用的 header 中需要身份验证 token ,因此我无法使用带有 url 的直接打开窗口。 代码是:
vm.downloadFile = function(fileId){
var action = baseHelpers.one('files/' + fileId + '/content').get();
action.then(function(result){});
}
最佳答案
我在.Net 服务器上有一个端点
[HttpPost]
[Route("api/tagExportSelectedToExcel")]
以及带有 axios 的 React 前端。任务是添加一个从该 API 下载文件的按钮。我花了几个小时才找到这个解决方案。我希望这对其他人有帮助。
这就是我所做的:
axios('/api/tagExportSelectedToExcel', {
data: exportFilter,
method: 'POST',
responseType: 'blob'
}).then(res => resolveAndDownloadBlob(res));
其中resolveAndDownloadBlob:
/**
* Resolved and downloads blob response as a file.
* FOR BROWSERS ONLY
* @param response
*/
function resolveAndDownloadBlob(response: any) {
let filename = 'tags.xlsx';
filename = decodeURI(filename);
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
link.remove();
}
关于javascript - 使用 javascript 从 API 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34509447/