Converting Files to Base64 in JavaScript
The FileReader API in JavaScript provides a straightforward way to convert files into their base64 representations. This can be particularly useful when sending files over networks or storing them in databases.
Converting a File to Base64
To convert a file to base64 using the FileReader API, follow these steps:
Example Code:
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
In the provided example, the getBase64() function takes a file object as an argument and converts it to base64 using the FileReader API. The base64 string can then be used for various purposes, such as sending via JSON or storing in a database.
The above is the detailed content of How Can I Convert Files to Base64 Encoding Using JavaScript's FileReader API?. For more information, please follow other related articles on the PHP Chinese website!