Get Base64 encode file-data from Input Form
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:
HTML:
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:
Asynchronous handling and you
Leverage the power of JavaScript async/await to master the asynchronous behaviors of file loading:
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:
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:
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.
Was this article helpful?