File Download In JavaScript

Ruslan Osipov
Author: Ruslan Osipov

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>
function downloadFile(url) {
    document.getElementById('download-file').src = url;

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;

NOTE: This will not work in IE11 and Opera Mini

Use fetch and blob

The modern approach

  .then(response => response.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a'); = 'none';
    a.href = url;
    link.setAttribute('download', 'new-file-name.txt');
  .catch(() => console.log('Ups, ...'));

That's it. Happy downloading!


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.