How do you download a file asynchronously using AJAX and Blob in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 2 days ago

How do you download a file asynchronously using AJAX and Blob in JavaScript?

message-square
0

To download a file asynchronously using AJAX and Blob in JavaScript, request the binary resource asynchronously with fetch() (or XMLHttpRequest / jQuery $.ajax() configured with responseType: "blob" / xhrFields: { responseType: "blob" }), validate the endpoint URL, HTTP status (response.ok), and Blob instance (blob instanceof Blob) using typeof / instanceof checks, generate a temporary object URL via URL.createObjectURL(blob), click a temporary <a download="..."> link to trigger the browser download, revoke the object URL via URL.revokeObjectURL(url), and wrap async execution and cleanup inside try / catch blocks—using a Map to store download metadata/registries so dynamic keys never collide with Object.prototype properties.


1. Asynchronous File Download via fetch() + Blob with Validation and try / catch

Validate the target URL, filename, and browser APIs, check response.ok before reading .blob(), trigger the anchor download, and revoke the object URL inside try / catch:

// Asynchronously fetch a file via AJAX/fetch(), convert to a Blob, and trigger a browser download
async function downloadFileAsyncWithBlob(fileUrl, fileName = "downloaded-file", {
  headers = {},
  revokeDelayMs = 1000
} = {}) {
  if (typeof fileUrl !== "string" || fileUrl.trim().length === 0) {
    throw new TypeError("Expected fileUrl to be a non-empty string.");
  }
  if (typeof fileName !== "string" || fileName.trim().length === 0) {
    throw new TypeError("Expected fileName to be a non-empty string.");
  }
  if (typeof headers !== "object" || headers === null || Array.isArray(headers)) {
    throw new TypeError("Expected headers to be a non-null plain/record object.");
  }
  if (typeof revokeDelayMs !== "number" || !Number.isFinite(revokeDelayMs) || revokeDelayMs < 0) {
    throw new RangeError("Expected revokeDelayMs to be a non-negative finite number.");
  }
  if (typeof fetch !== "function" || typeof Blob !== "function") {
    throw new Error("Browser fetch() and Blob APIs are required.");
  }
  if (typeof document === "undefined" || !(document instanceof Document)) {
    throw new Error("Browser Document environment is required to trigger a file download.");
  }
  if (typeof URL === "undefined" || typeof URL.createObjectURL !== "function" || typeof URL.revokeObjectURL !== "function") {
    throw new Error("Browser URL object URL APIs are required.");
  }

  const cleanUrl = fileUrl.trim();
  const cleanFileName = fileName.trim();

  try {
    const headersMap = new Map();
    for (const [key, val] of Object.entries(headers)) {
      if (typeof key === "string" && key.trim().length > 0 && typeof val === "string") {
        headersMap.set(key.trim(), val);
      }
    }

    const plainHeaders = {};
    for (const [k, v] of headersMap.entries()) {
      plainHeaders[k] = v;
    }

    const response = await fetch(cleanUrl, {
      method: "GET",
      headers: plainHeaders
    });

    if (!(response instanceof Response)) {
      throw new Error("Expected fetch() to resolve to a Response instance.");
    }
    if (!response.ok) {
      throw new Error(`File download request failed with HTTP ${response.status} (${response.statusText || "Error"}).`);
    }

    const fileBlob = await response.blob();
    if (!(fileBlob instanceof Blob)) {
      throw new Error("Expected response.blob() to return a Blob instance.");
    }

    const objectUrl = URL.createObjectURL(fileBlob);
    const anchorEl = document.createElement("a");
    if (!(anchorEl instanceof HTMLAnchorElement)) {
      URL.revokeObjectURL(objectUrl);
      throw new Error("Failed creating HTMLAnchorElement for download.");
    }

    anchorEl.href = objectUrl;
    anchorEl.download = cleanFileName;
    anchorEl.style.display = "none";

    document.body.appendChild(anchorEl);
    anchorEl.click();
    document.body.removeChild(anchorEl);

    setTimeout(() => {
      try {
        URL.revokeObjectURL(objectUrl);
      } catch (revokeError) {
        const revokeMsg = revokeError instanceof Error ? revokeError.message : String(revokeError);
        console.error(`Failed revoking Blob URL: ${revokeMsg}`);
      }
    }, revokeDelayMs);

    return new Map([
      ["fileName", cleanFileName],
      ["mimeType", fileBlob.type || "application/octet-stream"],
      ["byteSize", fileBlob.size],
      ["status", response.status]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed downloading file asynchronously from "${cleanUrl}": ${message}`);
  }
}

// Example usage:
// try {
//   const metaMap = await downloadFileAsyncWithBlob(
//     "https://example.com/files/monthly-statement.pdf",
//     "monthly-statement.pdf",
//     { headers: { Authorization: "Bearer <token>" } }
//   );
//   console.log("Downloaded:", metaMap.get("fileName"), "Bytes:", metaMap.get("byteSize"));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Verify response.ok before calling .blob(): If the server returns an HTTP 401, 403, 404, or 500 error page as a Blob, checking response.ok prevents saving an error payload as your target file.
  • Revoke object URLs with URL.revokeObjectURL(): Releases browser memory allocated for each generated Blob URL.

2. Asynchronous Blob Download with jQuery $.ajax() and Tracking Downloads in a Map

When using jQuery AJAX ($.ajax()) in legacy or jQuery-heavy codebases, set xhrFields: { responseType: "blob" } so jQuery does not corrupt binary data as text, and track active/completed downloads in a Map inside try / catch so dynamic keys never collide with Object.prototype properties:

// Download a file asynchronously via jQuery $.ajax() responseType "blob" and record metadata in a Map
function downloadFileWithJqueryAjax(fileUrl, fileName, downloadsMap = new Map(), {
  jqueryRef = (typeof $ !== "undefined" ? $ : null)
} = {}) {
  if (typeof jqueryRef !== "function") {
    throw new TypeError("Expected jqueryRef to be a valid jQuery ($) function.");
  }
  if (typeof fileUrl !== "string" || fileUrl.trim().length === 0) {
    throw new TypeError("Expected fileUrl to be a non-empty string.");
  }
  if (typeof fileName !== "string" || fileName.trim().length === 0) {
    throw new TypeError("Expected fileName to be a non-empty string.");
  }
  if (!(downloadsMap instanceof Map)) {
    throw new TypeError("Expected downloadsMap to be a Map instance.");
  }
  if (typeof document === "undefined" || !(document instanceof Document)) {
    throw new Error("Browser Document environment is required.");
  }
  if (typeof URL === "undefined" || typeof