File to Base64 Conversion in JavaScript
Converting a file into a base64 string is essential for various web applications. In JavaScript, this task can be achieved using the FileReader class.
Problem:
A user has obtained a File object using querySelector and aims to send it via JSON in base64 format. The question is how to convert this file to a base64 string.
Solution:
To convert a file to a base64 string, utilize the FileReader class as follows:
function getBase64(file) { var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { console.log(reader.result); // Base64 string }; reader.onerror = function (error) { console.log('Error: ', error); }; } var file = document.querySelector('#files > input[type="file"]').files[0]; getBase64(file);
In this code, the getBase64 function initializes a FileReader instance and begins reading the file as a data URL. When the reading operation is complete, the onload event handler is invoked, and it prints the base64 string to the console.
Note that the file obtained through querySelector is a File object, a subclass of Blob, making it compatible with the FileReader class. A complete working example is available for reference.
The above is the detailed content of How to Convert a File to a Base64 String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!