Obtaining a Blob from a DataURL
In certain scenarios, there is a need to transform arbitrary data into a Data URL using FileReader's readAsDataURL() method. However, can this Data URL be converted back into a Blob instance utilizing built-in browser APIs?
A solution has been proposed by a user named Matt:
Code Snippet:
<code class="js">function dataURItoBlob(dataURI) { // Convert base64 to raw binary data var byteString = atob(dataURI.split(',')[1]); // Extract the MIME component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] // Create an ArrayBuffer and Uint8Array var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); // Set the bytes of the buffer for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } // Create a Blob instance var blob = new Blob([ab], { type: mimeString }); return blob; }</code>
Note:
As mentioned in subsequent comments, BlobBuilder has become deprecated. Therefore, the code provided above is an updated version.
The above is the detailed content of Can You Convert a Data URL Back to a Blob in JavaScript Using Built-in APIs?. For more information, please follow other related articles on the PHP Chinese website!