How do you trigger a browser file download from JavaScript on button click? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you trigger a browser file download from JavaScript on button click?

message-square
0

To trigger a browser file download on a button click in JavaScript, create a Blob from your data (or fetch a file/resource as a Blob), generate a temporary object URL with URL.createObjectURL(blob), create an <a> element with its download attribute set to the desired filename, programmatically click it (link.click()), remove the temporary element, and release the object URL via URL.revokeObjectURL(url).


1. Downloading Generated Data (JSON, CSV, Text) via Blob and Object URL

Inside the button’s click event listener, build the file contents in memory, trigger the synthetic anchor click, and clean up the object URL:

// Trigger a client-side file download from text/JSON/CSV content on button click
function downloadTextFile(filename, content, mimeType = "application/json;charset=utf-8") {
  const blob = new Blob([content], { type: mimeType });
  const objectUrl = URL.createObjectURL(blob);

  const link = document.createElement("a");
  link.href = objectUrl;
  link.download = filename;
  link.style.display = "none";

  document.body.appendChild(link);
  link.click();

  link.remove();
  // Defer revocation slightly so the browser starts reading the object URL cleanly
  setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
}

const exportBtn = document.getElementById("export-json-btn");
if (exportBtn) {
  exportBtn.addEventListener("click", () => {
    const payload = { exportedAt: new Date().toISOString(), items: [1, 2, 3] };
    downloadTextFile("report-data.json", JSON.stringify(payload, null, 2));
  });
}
  • `new Blob([content], { type: mimeType }): Wraps strings or binary chunks with a MIME type so the browser recognizes the format.
  • **link.download = filename:** Instructs the browser to save the target as a file using filename` instead of merely navigating to it.
  • `URL.revokeObjectURL(objectUrl): Frees memory held by the object URL after download initiation.

2. Downloading a File from an API / Fetch Response on Click

When a backend endpoint returns a file stream, CSV, PDF, or binary payload—especially behind Authorization headers where a plain link cannot send custom headers—fetch the response as a Blob first and then trigger the download:

// Fetch a protected or dynamic file endpoint and download it on button click
async function downloadFromEndpoint(url, fallbackFilename = "download.bin") {
  const response = await fetch(url, { method: "GET" });
  if (!response.ok) {
    throw new Error(`Download failed with HTTP ${response.status}`);
  }

  const blob = await response.blob();
  const objectUrl = URL.createObjectURL(blob);

  const link = document.createElement("a");
  link.href = objectUrl;
  link.download = fallbackFilename;
  document.body.appendChild(link);
  link.click();
  link.remove();

  setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
}

const downloadReportBtn = document.getElementById("download-report-btn");
if (downloadReportBtn) {
  downloadReportBtn.addEventListener("click", async () => {
    downloadReportBtn.disabled = true;
    try {
      await downloadFromEndpoint("/api/exports/summary.csv", "summary.csv");
    } catch (err) {
      console.error("Export error:", err.message);
    } finally {
      downloadReportBtn.disabled = false;
    }
  });
}
  • Works with authenticated requests: fetch() lets you include headers or cookies and inspect response.ok before creating a file.
  • Button disabled state while downloading: Prevents duplicate clicks during an async fetch() download.

3. Common Traps to Avoid

Programmatic browser downloads often run into a few pitfalls:

  • Revoking URL.createObjectURL() synchronously on the very next line: Calling URL.revokeObjectURL(url) immediately after link.click() can interrupt or fail the download in some browsers before the download task reads the URL—revoke it asynchronously after a short delay.
  • Expecting the download attribute to rename cross-origin URLs: For cross-origin URLs without matching CORS / Content-Disposition headers, browsers may ignore link.download or open the resource instead of forcing a save with your custom filename.
  • Not handling fetch() HTTP errors before calling response.blob(): If an API returns a 401 or 404 JSON error, response.blob() would otherwise save the error text as the downloaded file unless you check response.ok first.

TL;DR: Create a Blob, pass it to URL.createObjectURL(), click a temporary <a download="file.ext"> element, remove the element, and call URL.revokeObjectURL() after a brief delay.

Are you generating files client-side (like JSON or CSV), downloading files from a fetch() API endpoint, or handling cross-origin file URLs?