JavaScript Download File

JavaScript Download File

There are several ways to download files in JavaScript.

Use iFrame

The easy way is to use invisible 'iframe':

<iframe id="download-file" style="display:none;"></iframe>
<script>
function downloadFile(url) {
    document.getElementById('download-file').src = url;
};
</script>

Create a link

Another way to download a file is to programmatically create a link, trigger the click event and delete the link from the DOM.

function downloadFile(url, name='default-file-name')
{
    let link = document.createElement('a');
    link.setAttribute('download', name);
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    link.remove();
}

NOTE: This will not work in IE11 and Opera Mini

Use fetch and blob

The modern approach

fetch('https://storage.com/file-url.txt')
  .then(response => response.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.style.display = 'none';
    a.href = url;
    link.setAttribute('download', 'new-file-name.txt');
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
  })
  .catch(() => console.log('Ups, ...'));

That's it. Happy downloading!

Related articles

Ruslan Osipov
Written by author: Ruslan Osipov