Converting Files to Base64 in JavaScript: A Comprehensive Guide
When working with web applications, you may often need to transmit files as part of data exchange. To achieve this seamlessly, converting files to Base64 format becomes necessary. This enigmatic encoding technique represents binary data using a subset of printable ASCII characters, making it suitable for transmitting files via HTTP or other text-based protocols.
Problem:
Suppose you have a File object obtained through the document.querySelector method:
file = document.querySelector('#files > input[type="file"]').files[0];
Your goal is to convert this File object to a Base64 string for efficient data transfer.
Solution:
To transform the file into Base64, you can utilize the FileReader class provided by JavaScript. This class allows you to read file contents and encode them into Base64 format. Here's how you can implement it:
function getBase64(file) { var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { console.log(reader.result); }; reader.onerror = function (error) { console.log('Error: ', error); }; } var file = document.querySelector('#files > input[type="file"]').files[0]; getBase64(file); // prints the Base64 string
This code initializes the FileReader instance and initiates the reading of the file as a Data URL (DataURL). Once the read operation completes successfully, the onload event is triggered, and the converted Base64 string is obtained from the reader.result. You can now use this Base64 string for data exchange or any other desired purpose.
The above is the detailed content of How to Convert Files to Base64 in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!