title: How to download large file with JavaScript
body: <p>I need to download a large file with JavaScript using <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest" rel="noreferrer">XMLHttpRequest</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" rel="noreferrer">fetch</a> without saving the file first in the RAM-Memory. </p>
  
  <p>Normal link download doesn't work for me, because I need to send a  Bearer Token in the header of the request. </p>
  
  <p>I could manage to download a file, but this "solution", it's saving the file first in the RAM-Memory, before I get a save dialog, so that the Browser will brake if the file is larger then the available RAM-Memory.</p>
  
  <p>Here is my "solution" with fetch:</p>
  
  <pre><code>        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)=&gt; {
                  return response.blob();
              })
              .then((myBlob)=&gt; {
                  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();
              });
  </code></pre>
  
  <p>And here is my "solution" with XMLHttpRequest:</p>
  
  <pre><code>        var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = ()=&gt;{
              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();
  </code></pre>
  
  <p>The question is how can I download files larger then the available RAM-Memory and in the same time setting the headers?</p>