Home > Web Front-end > JS Tutorial > How Can I Convert Files to Base64 Encoding Using JavaScript's FileReader API?

How Can I Convert Files to Base64 Encoding Using JavaScript's FileReader API?

DDD
Release: 2024-11-30 11:05:21
Original
271 people have browsed it

How Can I Convert Files to Base64 Encoding Using JavaScript's FileReader API?

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:

  1. Create a FileReader object: Initialize a FileReader instance.
  2. Load the file: Use the readAsDataURL() method to load the file content into the FileReader object.
  3. On load event: The FileReader object emits a load event when the file content is fully loaded.
  4. Obtain the base64 string: Access the result property of the FileReader object to obtain the file content as a base64-encoded string.

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template