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