The open blogging platform. Say no to algorithms and paywalls.

How To Create and Download Files in the Browser With Vanilla JavaScript

I wondered how easy it is

Source: the author

Source: the author

Ever wondered how web apps generate files and let you download them?

A common way is generating the file in the backend. Then, a redirect to the file in the browser is happening, which leads to an download. But there is another way: Files can be generated and downloaded in the browser. We don't even need a JavaScript library for this to happen. Here is how it works.

Generating a file with JavaScript

For working with files, there is an API in the browser. It is called the File API and is widely supported. To create a file with it, we create a new instance of the File class. It's as easy as the following code:

const file = new File(['foo'], 'note.txt', {
  type: 'text/plain',

The necessary parameters are the following:

  • First, an array of data — this can be a Blob, an ArrayBuffer, or like in our case, a compatible string.

  • Second, the filename, including the ending.

  • As an option, we pass the actual type of file.

For generating a file, file with data of the text/plain type (text, HTML, CSV, etc.), this is all we need. Generating more abstract file types requires working with blobs or buffers.

For now, this is enough. We created a new txt file in the browser. So, what's next?

Downloading the file

To check whether creating the file worked, we need to access it. Accessing it requires downloading. To download the file, we use a small trick:

We generate a link containing the reference to our file. Then, we let JavaScript click the link, so the file gets downloaded. But from where do we get the URL where our file is lying in the browser?

To receive our files URL, we use URL.createObjectURL() which receives our file object as a parameter. Then, specify the name the saved file should have by default with setting the download attribute of the link.

Finally, we mount the link in the DOM, click it artificially, and remove it from the DOM. Here is the full code:

That's it already — thank you for reading!

Continue Learning