How do you convert a Base64 string into a downloadable Blob in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you convert a Base64 string into a downloadable Blob in JavaScript?

message-square
0

To convert a Base64 string into a downloadable Blob in JavaScript, validate that the Base64 payload and MIME type are non-empty strings (typeof base64Input === "string" and typeof mimeType === "string"), strip any data:...;base64, prefix if present, decode the Base64 characters into a Uint8Array inside a try / catch block (handling invalid Base64 characters/lengths cleanly), build a new Blob([byteArray], { type: mimeType }), trigger a download with URL.createObjectURL(blob) and a temporary <a download="..."> element before revoking with URL.revokeObjectURL(url), and store file/download metadata in a Map so dynamic keys never collide with Object.prototype properties.


1. Converting a Base64 String into a Blob with Input Validation and try / catch

Validate base64Input and mimeType, normalize optional data: URI headers, decode bytes into a Uint8Array, and construct a Blob inside try / catch:

// Convert a raw Base64 string or data URL into a Blob safely
function convertBase64ToBlob(base64Input, mimeType = "application/octet-stream") {
  if (typeof base64Input !== "string" || base64Input.trim().length === 0) {
    throw new TypeError("Expected base64Input to be a non-empty string.");
  }
  if (typeof mimeType !== "string" || mimeType.trim().length === 0) {
    throw new TypeError("Expected mimeType to be a non-empty string.");
  }
  if (typeof atob !== "function" || typeof Blob !== "function" || typeof Uint8Array !== "function") {
    throw new Error("Base64 decoding (atob), Uint8Array, and Blob APIs are required.");
  }

  try {
    const trimmedInput = base64Input.trim();
    const commaIndex = trimmedInput.indexOf(",");
    const rawBase64 = trimmedInput.startsWith("data:") && commaIndex !== -1
      ? trimmedInput.slice(commaIndex + 1).replace(/\s+/g, "")
      : trimmedInput.replace(/\s+/g, "");

    if (rawBase64.length === 0 || !/^[A-Za-z0-9+/=]+$/.test(rawBase64) || rawBase64.length % 4 === 1) {
      throw new SyntaxError("Invalid Base64 string format or length.");
    }

    const binaryString = atob(rawBase64);
    const byteLength = binaryString.length;
    const byteArray = new Uint8Array(byteLength);

    for (let i = 0; i < byteLength; i += 1) {
      byteArray[i] = binaryString.charCodeAt(i);
    }

    const cleanMime = mimeType.trim();
    return new Blob([byteArray], { type: cleanMime });
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed converting Base64 string to Blob: ${message}`);
  }
}

// Example usage:
// try {
//   const sampleBase64 = "SGVsbG8sIEJhc2U2NCBCbG9iIQ=="; // "Hello, Base64 Blob!"
//   const textBlob = convertBase64ToBlob(sampleBase64, "text/plain;charset=utf-8");
//   console.log("Blob size (bytes):", textBlob.size, "Type:", textBlob.type);
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Strip the data:<mime>;base64, prefix before calling atob(): Passing a full data URL header directly into atob() fails due to invalid characters (data:, ;, =).
  • Populate a Uint8Array via charCodeAt() rather than passing a raw binary string directly: Ensures exact byte values (0-255) are preserved across binary files (PDFs, images, archives).

2. Triggering a Browser Download from Base64 and Tracking Metadata in a Map

In a browser environment, validate document instanceof Document, URL.createObjectURL, and fileName, trigger the download via an anchor element, revoke the temporary object URL, and return metadata in a Map inside try / catch:

// Convert a Base64 string to a Blob and trigger a browser download, returning metadata in a Map
function downloadBase64AsFile(base64Input, fileName = "download.bin", mimeType = "application/octet-stream") {
  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.createObjectURL() and URL.revokeObjectURL() are required.");
  }
  if (typeof fileName !== "string" || fileName.trim().length === 0) {
    throw new TypeError("Expected fileName to be a non-empty string.");
  }

  try {
    const blob = convertBase64ToBlob(base64Input, mimeType);
    const objectUrl = URL.createObjectURL(blob);
    const cleanFileName = fileName.trim();

    const anchor = document.createElement("a");
    if (!(anchor instanceof HTMLAnchorElement)) {
      throw new Error("Failed creating HTMLAnchorElement for download.");
    }

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

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

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

    return new Map([
      ["fileName", cleanFileName],
      ["mimeType", blob.type],
      ["byteSize", blob.size]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed downloading Base64 file "${fileName}": ${message}`);
  }
}

// Example usage (in browser):
// try {
//   const metaMap = downloadBase64AsFile(
//     "SGVsbG8gZnJvbSBCYXNlNjQ=",
//     "hello.txt",
//     "text/plain;charset=utf-8"
//   );
//   console.log("Downloaded:", metaMap.get("fileName"), "Bytes:", metaMap.get("byteSize"));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Use Map for download metadata: Avoids Object.prototype collisions (constructor, toString, hasOwnProperty) on dynamic or external metadata keys.
  • Revoke object URLs after download dispatch: Prevents memory retention from unrevoked Blob URLs in long-lived single-page apps.

3. URL-Safe Base64, Large Payloads, and MIME Type Caveats

Keep these Base64-to-Blob edge cases in mind in production code:

  • URL-safe Base64 uses - and _ (and optional padding =): Convert - to + and _ to /, and restore = padding to a multiple of 4 before calling atob() when handling JWT or URL-safe tokens.
  • Set an accurate mimeType: Although <a download="report.pdf"> controls the saved filename, setting the right Blob MIME type helps browsers and OS file handlers recognize the content cleanly.
  • Base64 expands size by ~33% over raw binary: Very large files are better transferred as binary (ArrayBuffer / Blob / fetch()) rather than Base64 strings when control over the transport layer exists.