Home > Article > Web Front-end > Can you convert a Data URL back into a Blob using JavaScript?
Question:
Using FileReader's readAsDataURL() method, one can convert data into a Data URL. However, is there a method to reverse this process and create a Blob instance from the Data URL using built-in browser APIs?
Answer:
A solution was proposed by Matt a year ago in the discussion thread "How to convert dataURL to file object in javascript?"
Updated Code:
Since BlobBuilder has been deprecated, here's the updated code:
<code class="javascript">function dataURItoBlob(dataURI) { // Convert base64 to raw binary data as a string let byteString = atob(dataURI.split(',')[1]); // Extract the MIME type let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // Convert the string to an ArrayBuffer let ab = new ArrayBuffer(byteString.length); let ia = new Uint8Array(ab); // Set the ArrayBuffer bytes to the appropriate values for (let i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } // Create a Blob from the ArrayBuffer let blob = new Blob([ab], { type: mimeString }); return blob; }</code>
The above is the detailed content of Can you convert a Data URL back into a Blob using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!