Home >Web Front-end >JS Tutorial >How Do I Convert Files to Base64 Encoding in JavaScript?

How Do I Convert Files to Base64 Encoding in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-01 06:22:12535browse

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:

  1. Obtain the File Object:

    • Utilize document.querySelector() to select the file input element.
    • Retrieve the file object from the files array at index 0.
  2. Convert to Base64 using FileReader:

    • Create a FileReader object.
    • Call readAsDataURL on the FileReader object, passing the file object as an argument.
    • In the onload event handler:

      • The base64 string is available in reader.result.
  3. 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

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn