As per some of the other answers, you can definitely use window.fetch and download.js to download a file. However, using window.fetch with blob has the restriction on memory imposed by the browser, and the download.js also has its compatibility restrictions.
If you need to download a big-sized file, you don't want to put it in the memory of the client side to stress the browser, right? Instead, you probably prefer to download it via a stream. In such a case, using an HTML link to download a file is one of the best/simplest ways, especially for downloading big-sized files via a stream.
Step One: create and style a link element
You can make the link invisible but still actionable.
HTML:
<a href="#" class="download-link" download>Download</a>
CSS:
.download-link {
position: absolute;
top: -9999px;
left: -9999px;
opacity: 0;
}
Step Two: Set the href
of the link, and trigger the click
event
JavaScript
let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;
const downloadLink = document.querySelector('.download-link')
downloadLink.href = url + '&ts=' + new Date().getTime() // Prevent cache
downloadLink.click()
Notes:
- You can dynamically generate the link element if necessary.
- This approach is especially useful for downloading, via a stream, big-sized files that are dynamically generated on the server side
https://www.googleapis.com/drive/v2/files/${fileId}?alt=media
– Alvarez<a>
element with adownload
attribute and simulating a click on that element, all with the use of JavaScript. See Zibri's answer (which, btw, was posted way after my comment). – Alvarez