javascript - 快速 blob 下载

标签 javascript streaming blob

我正在使用此代码从我的网络 API 下载文件:

function download(name){
    axios.get(api + "?filename="+name, { responseType: 'blob' })
        .then(res => {
            let blob = new Blob([res.data]);
            let a = document.createElement("a");
            document.body.appendChild(a);
            a.href = window.URL.createObjectUrl(blob);
            a.download = name;
            a.click();
            window.URL.revokeObjectUrl(url);
            a.remove();
        }
    );
}

当下载小文件时这段代码很棒,但当下载大文件时(例如 400mb) 代码等待 blob 读取全部内容,然后才在 chrome 下载管理器中“开始下载”,这对客户端来说非常不直观。

有没有办法将 blob“流”到文件系统?而不是必须等待文件完全到达我客户端的 RAM,然后才在下载管理器中显示下载?

已解决

我没有通过 axios 库下载文件,而是将浏览器指向下载链接,因为它只是一个 GET 请求。

function download(name){
    let a = document.createElement("a");
    document.body.appendChild(a);
    a.href = api + "?filename="+name;
    a.click();
    a.remove();
}

只需要将服务器端的 ContentDisposition header 设置为附件,并指定一个文件名,因为下载属性在某种程度上不适用于此方法。

同时指定 ContentLength 将允许浏览器估计下载时间

最佳答案

如果您需要下载 POST 请求的响应或者您的请求需要某种高级身份验证,而不是使用 axios 库,您可以尝试使用 native fetch 方法。

fetch(options)
  .then(res => res.blob())
  .then(blob => {
    // use blob
  });

您可以查看完整的response API here .

关于javascript - 快速 blob 下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53913512/

相关文章:

html - 将 http 实时流式传输到 HTML5 视频客户端的最佳方法

javascript - React 中的 HTML5 音频标签

javascript - 动态 IFRAME 在 IE11 中具有未定义的主体

javascript - 使用 YUI 3 格式化输入数据

javascript - 将视频流式传输到 Web 浏览器

apache-spark - 无法使用Spark读取kafka主题数据

php - 图像无法显示,因为它包含错误

azure 的 Blob - 几个大的或多个小的

javascript - 在 IE11 中读取 Blob

javascript - angularjs ng-click 函数参数不适用于 ng-repeat