Home > Web Front-end > JS Tutorial > body text

How to Convert a Blob to a Base64 String Using JavaScript?

Mary-Kate Olsen
Release: 2024-11-20 00:40:03
Original
430 people have browsed it

How to Convert a Blob to a Base64 String Using JavaScript?

Convert Blob to Base64 String with FileReader

To convert a Blob object to a Base64 string, you can use the FileReader API as follows:

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

The readAsDataURL method encodes the Blob object to Base64. The onloadend event will trigger once the encoding is complete, and the resulting Base64 string can be accessed via the base64data variable.

Using jQuery

jQuery provides a straightforward way to achieve the same result with the following code:

$.ajax({
  url: '<api-endpoint>',
  type: 'POST',
  contentType: false,
  processData: false,
  data: blob,
  success: function(data, status, xhr) {
    var base64data = xhr.getResponseHeader('Content-Type');
  }
});
Copy after login

The getResponseHeader method can be used to extract the Base64-encoded string from the server response.

Note: The resulting Base64 string will include the data URL declaration, which needs to be removed if only the encoded data is desired. This can be achieved by stripping the "data:/;base64," prefix from the result.

The above is the detailed content of How to Convert a Blob to a Base64 String Using 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