如何使用JavaScript下载大文件

时间:2017-10-25 12:16:40

标签: javascript xmlhttprequest fetch-api

我需要使用XMLHttpRequestfetch使用JavaScript下载大文件,而不将文件首先保存在RAM-Memory中。

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

我可以设法下载一个文件,但这个“解决方案”,在我得到一个保存对话框之前,它首先将文件保存在RAM-Memory中,这样如果文件大于可用的RAM,浏览器将会制动-Memory。

这是我使用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-Memory的文件,同时设置标题?

1 个答案:

答案 0 :(得分:0)

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

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

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