Home > Web Front-end > JS Tutorial > How to Convert a File to a Base64 String in JavaScript?

How to Convert a File to a Base64 String in JavaScript?

Mary-Kate Olsen
Release: 2024-12-02 04:59:09
Original
291 people have browsed it

How to Convert a File to a Base64 String in JavaScript?

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template