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!