How to Decode Base64 Back to a File

Convert a Base64 string back to a downloadable file. Learn how to decode Base64 to binary in JavaScript, Python, and Node.js with working examples.

Decoding

Detailed Explanation

Decoding Base64 back to a file reverses the encoding process: you take a Base64 string, convert it to raw binary bytes, and write those bytes as a file. This is commonly needed when you receive file data transmitted as Base64 through an API, a database, or a JSON payload.

In the browser (triggering a download):

function downloadBase64File(base64Data, fileName, mimeType) {
  const byteCharacters = atob(base64Data);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  const blob = new Blob([byteArray], { type: mimeType });
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(link.href);
}

The key step is converting the decoded string into a Uint8Array before creating a Blob. Passing the decoded string directly to the Blob constructor would encode it as UTF-8 text, which corrupts binary data.

In Node.js:

const fs = require("fs");
const base64Data = "iVBORw0KGgo..."; // your Base64 string
const buffer = Buffer.from(base64Data, "base64");
fs.writeFileSync("output.png", buffer);

In Python:

import base64
with open("output.png", "wb") as f:
    f.write(base64.b64decode(encoded_string))

Common gotchas:

  • If the Base64 string includes a data URI prefix like data:image/png;base64,, you must strip that prefix before decoding. Only the part after the comma is actual Base64 data.
  • Always use binary write mode ("wb" in Python, no encoding option in Node.js) when writing to disk. Text mode will corrupt the file on some platforms.
  • Verify the decoded file by checking its size and opening it. A corrupted Base64 string (truncated or with wrong characters) will produce a broken file without necessarily throwing an error.

Use Case

Reconstructing PDF attachments from a CRM API that returns document data as Base64-encoded strings within JSON responses.

Try It — Base64 Encoder

Open full tool