Base64 to File Converter

Free online tool to convert Base64 strings back to files. Supports all file types including documents, images, audio, video, and more. Fast, secure, and works entirely in your browser.

Why Use Base64 to File Converter?

Universal File Support

Convert any file type - documents, images, audio, video, archives, and more

Secure & Private

All processing happens in your browser. No files uploaded to servers.

Large File Support

Convert files up to 25MB in size

Instant Results

Get Base64 output immediately with copy and download options

Implementation Examples

Learn how to convert files to Base64 in your favorite programming language. All examples include complete, working code for handling various file types.

How to Convert Base64 to File with JavaScript

// Convert file to Base64
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      const base64 = reader.result; // Includes data URL prefix
      resolve(base64);
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// Usage with file input
document.querySelector('input[type="file"]').addEventListener('change', async (e) => {
  const file = e.target.files[0];
  const base64 = await fileToBase64(file);
  console.log(base64); // data:application/pdf;base64,JVBERi0x...

  // Get only Base64 string (without prefix)
  const base64Only = base64.split(',')[1];

  // Get file info
  console.log('File name:', file.name);
  console.log('File size:', file.size, 'bytes');
  console.log('File type:', file.type);
});

// Convert multiple files
async function convertMultipleFiles(files) {
  const results = [];

  for (const file of files) {
    const base64 = await fileToBase64(file);
    results.push({
      name: file.name,
      type: file.type,
      size: file.size,
      base64: base64.split(',')[1]
    });
  }

  return results;
}

How to Convert Base64 to File with Python

import base64
import os

# Convert file to Base64
def file_to_base64(file_path):
    with open(file_path, "rb") as file:
        encoded = base64.b64encode(file.read())
        return encoded.decode('utf-8')

# Usage
base64_string = file_to_base64("document.pdf")
print(f"Base64 length: {len(base64_string)}")

# Get file info
import mimetypes

def file_to_base64_with_info(file_path):
    # Get MIME type
    mime_type = mimetypes.guess_type(file_path)[0]

    # Get file size
    file_size = os.path.getsize(file_path)

    # Encode to Base64
    with open(file_path, "rb") as file:
        base64_str = base64.b64encode(file.read()).decode('utf-8')

    return {
        'filename': os.path.basename(file_path),
        'mime_type': mime_type,
        'size': file_size,
        'base64': base64_str
    }

# Convert multiple files
def convert_directory(directory_path):
    results = []

    for filename in os.listdir(directory_path):
        file_path = os.path.join(directory_path, filename)

        if os.path.isfile(file_path):
            result = file_to_base64_with_info(file_path)
            results.append(result)

    return results

# Usage with JSON
import json

file_data = file_to_base64_with_info("document.pdf")
json_output = json.dumps(file_data, indent=2)
print(json_output)

How to Convert Base64 to File with PHP

<?php
// Convert file to Base64
function fileToBase64($filePath) {
    $fileData = file_get_contents($filePath);
    $base64 = base64_encode($fileData);

    // Get MIME type
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $filePath);
    finfo_close($finfo);

    return [
        'filename' => basename($filePath),
        'mime_type' => $mimeType,
        'size' => filesize($filePath),
        'base64' => $base64
    ];
}

// Usage
$result = fileToBase64("document.pdf");
echo "File: " . $result['filename'] . "\n";
echo "Size: " . $result['size'] . " bytes\n";
echo "Base64 length: " . strlen($result['base64']) . "\n";

// For API response
header('Content-Type: application/json');
echo json_encode($result);

// Convert uploaded file
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $tmpPath = $_FILES['file']['tmp_name'];
    $result = fileToBase64($tmpPath);

    // Send as JSON
    header('Content-Type: application/json');
    echo json_encode($result);
}

// Batch convert files
function convertMultipleFiles($directory) {
    $results = [];
    $files = glob($directory . '/*');

    foreach ($files as $file) {
        if (is_file($file)) {
            $results[] = fileToBase64($file);
        }
    }

    return $results;
}
?>

How to Convert Base64 to File with Node.js

const fs = require('fs').promises;
const path = require('path');
const mime = require('mime-types');

// Convert file to Base64
async function fileToBase64(filePath) {
  const buffer = await fs.readFile(filePath);
  return buffer.toString('base64');
}

// Get file info with Base64
async function fileToBase64WithInfo(filePath) {
  const stats = await fs.stat(filePath);
  const buffer = await fs.readFile(filePath);
  const base64 = buffer.toString('base64');
  const mimeType = mime.lookup(filePath) || 'application/octet-stream';

  return {
    filename: path.basename(filePath),
    mimeType,
    size: stats.size,
    base64
  };
}

// Usage
(async () => {
  const result = await fileToBase64WithInfo('document.pdf');
  console.log('File:', result.filename);
  console.log('Size:', result.size, 'bytes');
  console.log('Base64 length:', result.base64.length);
})();

// Express.js API endpoint
const express = require('express');
const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() });
const app = express();

app.post('/api/file/encode', upload.single('file'), async (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: 'No file uploaded' });
  }

  const base64 = req.file.buffer.toString('base64');

  res.json({
    filename: req.file.originalname,
    mimeType: req.file.mimetype,
    size: req.file.size,
    base64
  });
});

// Convert multiple files
async function convertDirectory(directoryPath) {
  const files = await fs.readdir(directoryPath);
  const results = [];

  for (const file of files) {
    const filePath = path.join(directoryPath, file);
    const stats = await fs.stat(filePath);

    if (stats.isFile()) {
      const result = await fileToBase64WithInfo(filePath);
      results.push(result);
    }
  }

  return results;
}

Share this tool

Help others discover this free Base64 tool

or