How To Prompt The User To Download A File

Sometimes we just want to download an image file instead of opening it in the browser. For these situations we can use the download attribute. In this article we’ll learn how to use it and how we can automate its behavior with JavaScript.

The download attribute tells the browser to download a link target when it’s clicked.

<a href="/media/cat.jpeg" download>cat.jpeg</a>

Try it here: cat.jpeg

We can also supply the name of the file by setting the value of the download attribute, in this example we set it to 'my-cat.jpeg'.

<a href="/media/cat.jpeg" download="my-cat.jpeg">cat.jpeg</a>

Try it here: cat.jpeg

Automating the download

Suppose we’ve generated a file in the browser, how can we serve that file to the user without having to ask the user to click a link.

JavaScript to the rescue!

function downloadFile(file) {
    // Create a link and set the URL using `createObjectURL`
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = URL.createObjectURL(file);
    link.download = file.name;

    // It needs to be added to the DOM so it can be clicked
    document.body.appendChild(link);
    link.click();

    // To make this work on Firefox we need to wait
    // a little while before removing it.
    setTimeout(() => {
        URL.revokeObjectURL(link.href);
        link.parentNode.removeChild(link);
    }, 0);
}

We can use it like this:

// Dynamically create a File
const myFile = new File([`${new Date()}: Meow!`], 'my-cat.txt');

// Download it using our function
downloadFile(myFile);

Click on the button below to give it a go.

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

Or join my newsletter

More articles More articles