Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to download a file generated in the browser

Short answer

Put the data into a Blob, create a temporary address for it and click a link with the download attribute:

<button id="save">Download JSON</button>
<script>
  function downloadFile(content, fileName, type) {
    const blob = new Blob([content], { type });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(url);
  }
 
  document.getElementById('save').addEventListener('click', () => {
    const data = { name: 'Anna', score: 42 };
    downloadFile(JSON.stringify(data, null, 2), 'result.json', 'application/json');
  });
</script>

CSV for Excel

Build the lines of a table and join them with line breaks. The invisible character  at the start helps Excel read the letters correctly:

const rows = [['Name', 'Score'], ['Anna', 42], ['Oleg', 37]];
const csv = rows.map((row) => row.join(',')).join('\n');
 
downloadFile('' + csv, 'scores.csv', 'text/csv');

A file from the server

To download a file by address, a link with download is enough. For a file you received with fetch(), get its Blob:

const response = await fetch('/api/reports/7.pdf');
const blob = await response.blob();
const url = URL.createObjectURL(blob);

Common mistake

Every URL.createObjectURL() keeps the data in memory until the page is closed. Call URL.revokeObjectURL() when the address is no longer needed.

const url = URL.createObjectURL(blob);
link.href = url;
link.click();
URL.revokeObjectURL(url);

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.