Simple JavaScript File Download Helper featured image

Simple JavaScript File Download Helper

March 18, 2018 · 1 min read

In the future, web standards are expected to advance to facilitate a built-in client-side method for downloading files or JSON blobs. However, for now, the approach to initiating a file download in the client’s browser remains somewhat unconventional.

The current method involves creating a virtual anchor tag with a URL that links to the desired asset. A “click” event is then programmatically triggered, prompting the user to download the specified URL to their local device.

export const downloadFile = (data, name, mimeType) => {
  const dataStr = (typeof data === 'string')
    ? `data:${mimeType};charset=utf-8,${encodeURIComponent(data)}`
    : `data:${mimeType};charset=utf-8,${encodeURIComponent(JSON.stringify(data))}`;

  const downloadAnchorNode = document.createElement('a');
  
  downloadAnchorNode.setAttribute('href', dataStr);
  downloadAnchorNode.setAttribute('download', `${name}.${type}`);
  document.body.appendChild(downloadAnchorNode); // required for firefox
  downloadAnchorNode.click();
  downloadAnchorNode.remove();
};

This function could be expanded to type-check mimeType against the official MIME Content-Type list per MDN Docs for stricter validation.

Griffen Fargo headshot

Griffen Fargo

Published

Share
Keep Reading

Discussion

Have thoughts? Drop them in.

Comments are powered by Disqus. Sign in once, comment anywhere.

Loading comments…