Published at
Updated at
Reading time
1min

I'm just parking the following snippet for the future. ๐Ÿ™ˆ

Years ago, I had to fiddle around with dynamic file downloads in a single page application. And let me tell you that it was very painful. Rik Schennink shared a snippet to trigger file downloads. That code will come in handy for my future self!

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);
}

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

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

Thanks Rik!

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles