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
Linda HamiltonOriginal
2024-11-17 16:51:02761browse

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);
}

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);
  });
}

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!

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