Simple JavaScript File Download Helper

March 18, 2018

Simple JavaScript File Download Helper featured image

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 to verify it is an official Mime Content-Type per MDN Docs, or dee

headshot photo

Published on

March 18, 2018

griffen.codes

made with 💖 and

2024 © all rights are reserved | updated 16 seconds ago

Footer Background Image