JavaScript

Download File from Client

by @admin
12h ago
Apr 28, 2026
Public
Programmatically triggers a file download from a Blob, File object, or plain text/JSON string without a server round-trip. Creates a temporary anchor element with a download attribute and revokes the object URL after use to prevent memory leaks. Supports custom filenames and MIME types.
JavaScript
function downloadBlob(blob, filename) {
  const url = URL.createObjectURL(blob);
  const a   = Object.assign(document.createElement('a'), { href: url, download: filename });
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 10_000);
}

// Convenience wrappers
const downloadJSON = (data, filename = 'export.json') =>
  downloadBlob(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }), filename);

const downloadCSV = (rows, filename = 'export.csv') => {
  const csv = rows.map((r) => r.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
  downloadBlob(new Blob([csv], { type: 'text/csv' }), filename);
};

// Usage
downloadJSON({ users: [{ id: 1, name: 'Alice' }] }, 'users.json');
downloadCSV([['Name', 'Age'], ['Alice', 30], ['Bob', 25]], 'people.csv');
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.