javascript - 使用 javascript 从 API 下载文件

标签 javascript angularjs file blob restangular

我需要使用 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")]

以及带有 axiosReact 前端。任务是添加一个从该 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/

相关文章:

c - 使用 C 代码难以读取 DNA 序列文件

javascript - 网络音频API : Prevent microphone input from being played through speakers

java - 判断当前Javascript实现是否是Rhino

javascript - 从键盘输入时,每 n 个字符后加破折号

javascript - AngularJs - 从指令获取默认 HTML

c# - SQL:保存 MIME 类型或扩展名?

angularjs - 控制如何处理 $httpBackend.when() 中的每个捕获

javascript - 为什么我的内联 JS 破坏了我的 div 大小?

angularjs - Angular-ui modal - 将数据传递到模态

java - 正则表达式无法正确分解带有版本号的文件路径