Home > Web Front-end > JS Tutorial > How to Efficiently Convert a Blob from an HTML Form to a Base64 String?

How to Efficiently Convert a Blob from an HTML Form to a Base64 String?

Linda Hamilton
Release: 2024-11-17 16:51:02
Original
757 people have browsed it

How to Efficiently Convert a Blob from an HTML Form to a Base64 String?

Convert Blob to Base64

In this coding query, the user seeks to convert a blob, obtained from HTML form input, into a base64 string. The provided code successfully displays an image by creating a URL object using createObjectURL, but the desired conversion using readAsBinaryString results in a null source variable.

To resolve this issue and bypass the complexity of the provided code, a simpler solution utilizing the readAsDataURL method is presented below:

var reader = new FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function() {
  var base64data = reader.result;                
  console.log(base64data);
}
Copy after login

According to the FileReader documentation, readAsDataURL encodes the content as base64.

For asynchronous handling, an awaitable function can be defined as:

function blobToBase64(blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}
Copy after login

Note: To obtain the base64-encoded string alone, remove data:/;base64, from the result.

The above is the detailed content of How to Efficiently Convert a Blob from an HTML Form to a Base64 String?. 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