簡體   English   中英

如何使用JavaScript下載大文件

[英]How to download large file with JavaScript

我需要使用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的文件並同時設置標題?

如StreamSaver.js(下面的鏈接)中所示,您可以使用流來解決此問題。

您可以嘗試StreamSaver.js (免責聲明:我不是該回購的所有者)。 似乎解決了你想要的程度,它不是跨瀏覽器兼容的。 目前僅支持Chrome +52和Opera +39。

或者,有FileSaver.js (免責聲明:我不是該回購的所有者),但您遇到了當前遇到的相同問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM