Explain Codes LogoExplain Codes Logo

Get Base64 encode file-data from Input Form

javascript
file-reader-api
base64-encoding
async-await
Alex KataevbyAlex Kataev·Feb 8, 2025
TLDR

In one swift move, get a Base64 representation of a file using JavaScript and FileReader. Listen for a file selection, read that file as a data URL and capture the Base64 string on the load event:

document.getElementById('file').change = function() { let reader = new FileReader(); // reader.onload performs the magic trick~✨✨ reader.onload = () => console.log(reader.result.replace(/^data:.+;base64,/, '')); reader.readAsDataURL(this.files[0]); };

HTML:

<input type="file" id="file" />

Copy-paste this code snippet to get your file's Base64 representation in a flash.

Know your tools

Introduction to FileReader API

The FileReader API provides a handy toolbox for dealing with files in JavaScript—with four read methods to your disposal:

  • readAsArrayBuffer()
  • readAsBinaryString()
  • readAsDataURL()
  • readAsText()

readAsDataURL() is your shiny magic wand, creating a data: URL with the heart of the Base64 encoded data.

Tackling errors like a pro

Slip the file reading process into a try/catch block to handle exceptions, and let FileReader's onerror event handle any reading mishaps that might pop up:

reader.onerror = (error) => { console.error('Aha, caught you!', error); };

Asynchronous handling and you

Leverage the power of JavaScript async/await to master the asynchronous behaviors of file loading:

document.getElementById('file').onchange = async function() { try { let reader = new FileReader(); reader.onload = () => console.log(reader.result.replace(/^data:.+;base64,/, '')); reader.readAsDataURL(this.files[0]); } catch (error) { console.error('Something went wrong:', error); } };

Cleaning up the mess (Base64 string)

To achieve that picture-perfect, pure Base64 string (shiny, without the data URL prefix), just shake off the icky data: part:

let base64String = reader.result.replace(/^data:.+;base64,/, ''); // Now it's sparkly clean!✨✨

Avoiding the potholes

Cross-browser compatibility

Ensure your Jedi tricks work across all browsers. Double-check your usage of FileReader API and the readAsDataURL method against the darkness of browser compatibility tables.

King-sized files

For handling those heavy, chunky files, it's better to opt for readAsArrayBuffer and convert the ArrayBuffer to a base64 string using a dedicated conversion function. Because you don't want to be that guy who crashes the browser.

How to cope with complex files

Sometimes, simple Base64 encoding won't do. You've got binary data, or dealing with a multifile structure. Bring in backup reinforcements like the tar-js library to handle such trickier scenarios.

Mastering optimizations

Containing the mess with closures

Keep your variables tidied up and out of global scope through closures within your async event listener functions. Readable code is happy code!

Promises: Your best pals

Transform those FileReader callbacks to the sleek, modern Promises. Not only does your code look swoon-worthy, but flow control becomes a piece of cake:

const readFileAsBase64 = (file) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result.replace(/^data:.+;base64,/, '')); reader.onerror = reject; reader.readAsDataURL(file); }); document.getElementById('file').onchange = async function() { try { const base64 = await readFileAsBase64(this.files[0]); console.log(base64); } catch (error) { console.error('Did the file bite?', error); } };

Bonus tips for image files

Can you handle images with grace and finesse? Consider reducing the sizes of image files before they're Base64 encoded. All that glitters may not be gold—sometimes, it's an inefficiency warning.