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

Related articles

Ruslan Osipov
Written by author: Ruslan Osipov