💵 Website Ad Revenue Calculator

File Download In JavaScript

There are several ways to download file in JavaScript.

File download 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!

FAQs

Can I use iframe to download file in JavaScript?

Yes, you can use invisible 'iframe' and set it's source to the file URL.


What is the modern way to download file in JavaScript?

The modern way is to use fetch and blob.


How I can make link downloadable?

You can add 'download' attribute to the link tag and set it to the desired filename.