Home >Web Front-end >JS Tutorial >How Do I Convert Files to Base64 Encoding in JavaScript?
Converting Files to Base64 using JavaScript
To send files via JSON in base64, follow these steps:
Obtain the File Object:
Convert to Base64 using FileReader:
In the onload event handler:
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
Note that the File object can be used with FileReader because it's a subclass of Blob.
The above is the detailed content of How Do I Convert Files to Base64 Encoding in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!