如何使用JavaScript下载大文件

问题描述 投票:0回答:1

我需要使用 XMLHttpRequestfetch 使用 JavaScript 下载一个大文件,而不先将文件保存在 RAM 内存中。

普通链接下载对我不起作用,因为我需要在请求标头中发送不记名令牌。

我可以设法下载一个文件,但是这个“解决方案”,它首先将文件保存在 RAM 内存中,然后再出现保存对话框,这样如果文件大于可用 RAM 内存,浏览器就会停止运行.

这是我的 fetch 的“解决方案”:

        var myHeaders = new Headers();
        myHeaders.append('Authorization', `Bearer ${token}`);

        var myInit = { method: 'GET',
            headers: myHeaders,
            mode: 'cors',
            cache: 'default' };
        var a = document.createElement('a');

        fetch(url,myInit)
            .then((response)=> {
                return response.blob();
            })
            .then((myBlob)=> {
                a.href = window.URL.createObjectURL(myBlob);
                var attr = document.createAttribute("download");
                a.setAttributeNode(attr);
                a.style.display = 'none';
                document.body.appendChild(a);
                a.click();
                a.remove();
            });

这是我的 XMLHttpRequest 的“解决方案”:

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = ()=>{
            if (xhttp.readyState == 4){
                if ((xhttp.status == 200) || (xhttp.status == 0)){
                    var a = document.createElement('a');
                    a.href = window.URL.createObjectURL(xhttp.response); // xhr.response is a blob
                    var attr = document.createAttribute("download");
                    a.setAttributeNode(attr);
                    a.style.display = 'none';
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                }
            }
        };
        xhttp.open("GET", url);
        xhttp.responseType = "blob";
        xhttp.setRequestHeader('Authorization', `Bearer ${token}`);
        xhttp.send();

问题是如何下载大于可用 RAM 内存的文件并同时设置标头?

javascript xmlhttprequest fetch-api
1个回答
0
投票

如 StreamSaver.js(下面的链接)中所示,您可以使用流来解决此问题。

您可以尝试StreamSaver.js(免责声明:我不是该存储库的所有者)。似乎解决了你想要的问题,但它不兼容跨浏览器。目前仅 Chrome +52 和 Opera +39 支持。

或者,还有 FileSaver.js (免责声明:我不是该存储库的所有者),但您会遇到与当前遇到的相同问题。

© www.soinside.com 2019 - 2024. All rights reserved.