← Blog
Base64 JavaScript Python

How to Convert Base64 Back to a File (JS, Node.js & Python)

Step-by-step guide to decoding Base64 strings back to files in the browser, Node.js, and Python β€” with working code examples.

Β· GoGood.dev

You encounter Base64-encoded files constantly in development β€” JSON API responses with embedded PDFs, data URIs in HTML, email attachments, base64-encoded certificates in config files, uploaded images from forms. At some point you need to decode them back to the original file and save it.

The process is straightforward once you know the right API to use, but the details differ slightly between the browser, Node.js, and Python. This guide walks through each.

TL;DR: Convert Base64 back to a file instantly at GoGood.dev Base64 to File Converter β€” paste the Base64 string, it detects the file type, and downloads the original file. For code, use the Blob API in browsers, Buffer.from() in Node.js, or base64.b64decode() in Python.


What Is Base64 and Why Is It Used for Files?

Base64 converts binary data (image bytes, PDF content, encrypted blobs) into printable ASCII text. Every 3 bytes of binary become 4 text characters β€” a 33% size increase β€” but the output is safe to include in JSON, email headers, and text-based protocols that can’t handle raw bytes.

When you encounter Base64 in the wild:

REST API responses with embedded files:

{
  "document_id": "doc_456",
  "filename": "invoice.pdf",
  "content_type": "application/pdf",
  "data": "JVBERi0xLjQKJcfs3w0KdHJhaWxlciA8PC9TaXplIDc..."
}

Data URIs in HTML:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ..." />

Email attachments (MIME-encoded):

--boundary123
Content-Type: image/jpeg; name="photo.jpg"
Content-Transfer-Encoding: base64

/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/...

Configuration files with embedded certificates:

-----BEGIN CERTIFICATE-----
MIIEpQIBAAKCAQEA2Z3qX2BTLS39R3wvUL3p1JIiwic7o9F9z/R8qJ0TEFZ+...
-----END CERTIFICATE-----

To recover the original file, you decode the Base64 string and write the binary bytes to disk.


Method 1: Use the Online Converter (No Code)

The fastest way β€” no programming:

  1. Go to GoGood.dev Base64 to File Converter
  2. Paste your Base64 string in the input
  3. The tool auto-detects the file type from the MIME type prefix or magic bytes
  4. Click Download to save the original file

It handles any file format that was originally Base64-encoded.


Method 2: JavaScript (Browser) β€” Blob + Download

Convert Base64 to a downloadable file in the browser:

function base64ToFile(base64String, fileName, mimeType) {
  // Strip data URI prefix if present (data:application/pdf;base64,)
  const base64Data = base64String.replace(/^data:[^;]+;base64,/, '');

  // Decode Base64 to binary
  const byteCharacters = atob(base64Data);
  const byteNumbers = Array.from(byteCharacters, c => c.charCodeAt(0));
  const byteArray = new Uint8Array(byteNumbers);

  // Create Blob and download
  const blob = new Blob([byteArray], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(url);
}

// Usage
base64ToFile(
  'JVBERi0xLjQKJcfs3w0KdHJhaWxlciA8PC9TaXplIDc...',
  'document.pdf',
  'application/pdf'
);

How it works:

  1. atob() decodes the Base64 string to a binary string
  2. charCodeAt() converts each character to its byte value
  3. Uint8Array creates a typed array of bytes
  4. Blob wraps the bytes with a MIME type
  5. URL.createObjectURL() creates a download link
  6. Click the link to trigger the download
  7. revokeObjectURL() cleans up memory

Without the download β€” just get the Blob:

function base64ToBlob(base64String, mimeType) {
  const base64Data = base64String.replace(/^data:[^;]+;base64,/, '');
  const byteCharacters = atob(base64Data);
  const byteNumbers = Array.from(byteCharacters, c => c.charCodeAt(0));
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type: mimeType });
}

// Usage
const blob = base64ToBlob('iVBORw0KGgo...', 'image/png');
// Use blob for file upload, display, etc.

Display image in browser without downloading:

const base64String = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ...';
const blob = base64ToBlob(base64String, 'image/png');
const url = URL.createObjectURL(blob);
document.getElementById('image').src = url;

Send decoded file to server:

async function uploadDecodedFile(base64String, fileName, mimeType) {
  const blob = base64ToBlob(base64String, mimeType);

  const formData = new FormData();
  formData.append('file', blob, fileName);

  const response = await fetch('/api/upload', {
    method: 'POST',
    body: formData
  });

  return response.json();
}

Handle large files (chunked processing):

For very large Base64 strings, processing all at once can be slow. Decode in chunks:

function base64ToFileChunked(base64String, fileName, mimeType, chunkSize = 65536) {
  const base64Data = base64String.replace(/^data:[^;]+;base64,/, '');

  const chunks = [];
  for (let i = 0; i < base64Data.length; i += chunkSize) {
    const chunk = base64Data.slice(i, i + chunkSize);
    const byteCharacters = atob(chunk);
    const byteNumbers = Array.from(byteCharacters, c => c.charCodeAt(0));
    chunks.push(new Uint8Array(byteNumbers));
  }

  const blob = new Blob(chunks, { type: mimeType });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(url);
}

Method 3: Node.js (fs + Buffer)

In Node.js, use the fs module and Buffer:

const fs = require('fs');

function base64ToFile(base64String, outputPath) {
  // Strip data URI prefix if present
  const base64Data = base64String.replace(/^data:[^;]+;base64,/, '');

  // Decode Base64 to Buffer
  const buffer = Buffer.from(base64Data, 'base64');

  // Write to file
  fs.writeFileSync(outputPath, buffer);
}

// Usage
base64ToFile('JVBERi0xLjQKJcfs3w0K...', './documents/report.pdf');

Async version (recommended for large files):

const fs = require('fs').promises;

async function base64ToFileAsync(base64String, outputPath) {
  const base64Data = base64String.replace(/^data:[^;]+;base64,/, '');
  const buffer = Buffer.from(base64Data, 'base64');
  await fs.writeFile(outputPath, buffer);
}

// Usage
await base64ToFileAsync('JVBERi0xLjQK...', './documents/report.pdf');

Get the Buffer without writing to disk:

function base64ToBuffer(base64String) {
  const base64Data = base64String.replace(/^data:[^;]+;base64,/, '');
  return Buffer.from(base64Data, 'base64');
}

const buffer = base64ToBuffer('iVBORw0KGgo...');
// Use buffer for in-memory processing, sending via API, etc.

Send decoded file via API:

const fs = require('fs');
const https = require('https');

function uploadDecodedFile(base64String, fileName) {
  const base64Data = base64String.replace(/^data:[^;]+;base64,/, '');
  const buffer = Buffer.from(base64Data, 'base64');

  const options = {
    hostname: 'api.example.com',
    port: 443,
    path: '/upload',
    method: 'POST',
    headers: {
      'Content-Length': buffer.length,
      'Content-Type': 'application/octet-stream',
      'X-Filename': fileName
    }
  };

  const req = https.request(options, (res) => {
    console.log(`Status: ${res.statusCode}`);
  });

  req.write(buffer);
  req.end();
}

Decompress and save (e.g., gzip-compressed Base64):

const fs = require('fs');
const zlib = require('zlib');

function base64ToFileDecompressed(base64String, outputPath) {
  const base64Data = base64String.replace(/^data:[^;]+;base64,/, '');
  const buffer = Buffer.from(base64Data, 'base64');

  zlib.gunzip(buffer, (err, decompressed) => {
    if (err) throw err;
    fs.writeFileSync(outputPath, decompressed);
  });
}

Method 4: Python

In Python, use the base64 module:

import base64
import re

def base64_to_file(base64_string, output_path):
    # Strip data URI prefix if present
    base64_data = re.sub(r'^data:[^;]+;base64,', '', base64_string)

    # Decode Base64
    file_bytes = base64.b64decode(base64_data)

    # Write to file
    with open(output_path, 'wb') as f:
        f.write(file_bytes)

# Usage
base64_to_file('JVBERi0xLjQKJcfs3w0K...', './documents/report.pdf')

Get bytes without writing to file:

import base64

def base64_to_bytes(base64_string):
    return base64.b64decode(base64_string)

file_bytes = base64_to_bytes('iVBORw0KGgo...')
# Use bytes for in-memory processing

Handle different data formats:

import base64
import json

# Decode image
image_bytes = base64.b64decode(base64_string)

# Decode JSON
json_string = base64.b64decode(base64_string).decode('utf-8')
data = json.loads(json_string)

# Decode text
text = base64.b64decode(base64_string).decode('utf-8')

Auto-detect and save by file extension:

import base64
import magic  # pip install python-magic

def base64_to_file_auto(base64_string, output_dir='./downloads'):
    # Decode
    file_bytes = base64.b64decode(base64_string)

    # Detect MIME type and get extension
    mime_type = magic.from_buffer(file_bytes, mime=True)
    extensions = {
        'image/png': '.png',
        'image/jpeg': '.jpg',
        'application/pdf': '.pdf',
        'text/plain': '.txt',
        'application/json': '.json'
    }
    ext = extensions.get(mime_type, '.bin')

    # Save with timestamp
    from datetime import datetime
    filename = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}{ext}"
    filepath = f"{output_dir}/{filename}"

    with open(filepath, 'wb') as f:
        f.write(file_bytes)

    return filepath

Handling Different File Types (PDF, PNG, ZIP)

The MIME type prefix in a data URI tells you the file format:

data:application/pdf;base64,JVBERi0xLjQK...      β†’ PDF
data:image/png;base64,iVBORw0KGgo...            β†’ PNG
data:image/jpeg;base64,/9j/4AAQSkZJ...          β†’ JPEG
data:application/zip;base64,UEsDBAoA...         β†’ ZIP
data:text/plain;base64,SGVsbG8gV29...           β†’ Plain text

If the prefix isn’t present, inspect the first few bytes (magic bytes) to identify the file:

function detectFileType(base64String) {
  const byteCharacters = atob(base64String.slice(0, 20));
  const bytes = Array.from(byteCharacters, c => c.charCodeAt(0));

  // Check magic bytes
  if (bytes[0] === 0xFF && bytes[1] === 0xD8) return 'image/jpeg';
  if (bytes[0] === 0x89 && bytes[1] === 0x50) return 'image/png';
  if (bytes[0] === 0x25 && bytes[1] === 0x50) return 'application/pdf';
  if (bytes[0] === 0x50 && bytes[1] === 0x4B) return 'application/zip';

  return 'application/octet-stream'; // unknown
}

FAQ

How do I know what file type a Base64 string is?

Check the data URI prefix (data:TYPE;base64,...). If there’s no prefix, use magic bytes β€” the first few bytes of the file usually identify the type. For example, PDFs always start with %PDF, PNG files start with specific byte sequences. Most tools like GoGood.dev Base64 Converter auto-detect using magic bytes.

Can I convert Base64 to PDF?

Yes. PDFs are just binary files. Decode the Base64 string to bytes and write to a .pdf file. If you received the Base64 from a JSON API, the MIME type should be application/pdf. Use the methods above with outputPath ending in .pdf.

Why does my decoded file appear corrupted?

Most likely cause: you stripped the padding = characters or included carriage returns/newlines in the Base64 string. Base64 strings should be continuous without line breaks. Remove any whitespace before decoding:

const cleanBase64 = base64String.replace(/\s/g, '');

Or the file was corrupted during encoding. If you control both sides, verify the encoding is correct before decoding.

What’s the size difference between Base64 and the original file?

Base64 is approximately 33% larger. A 100 KB binary file becomes ~133 KB when Base64-encoded. This 33% overhead comes from the encoding scheme β€” every 3 bytes become 4 characters.

When you decode back to the original, you recover the original file size exactly.

Can I decode without downloading to disk?

Yes. In the browser, create a Blob and display it without downloading:

const blob = base64ToBlob(base64String, 'image/png');
const url = URL.createObjectURL(blob);
document.getElementById('image').src = url;

In Node.js, keep the bytes in a Buffer:

const buffer = Buffer.from(base64String, 'base64');
// Use buffer for in-memory processing

In Python, work with the bytes directly:

file_bytes = base64.b64decode(base64_string)
# Use file_bytes without writing to disk

For quick conversion without writing code, use GoGood.dev Base64 to File Converter. Paste the Base64 string, select or auto-detect the file type, and download the original.

For more on Base64: Base64 Encode and Decode Explained covers how Base64 works and why it exists, and How to Convert an Image to Base64 walks through encoding images into Base64 in the first place.