Home > Article > Web Front-end > How to Convert a Data URL to a Blob in JavaScript?
Converting Data URLs to Blobs
Transforming arbitrary data into a Data URL using FileReader's readAsDataURL() is a useful technique. However, what if you need to convert that Data URL back into a Blob instance?
Browser-Native Conversion
Currently, there is no built-in browser API that directly converts Data URLs to Blobs. However, there are workaround solutions that utilize custom JavaScript code.
Custom JavaScript Solution
A widely accepted method was proposed by Matt on Stack Overflow (How to convert dataURL to file object in javascript?). Here's an updated version of his code:
<code class="javascript">function dataURItoBlob(dataURI) { const byteString = atob(dataURI.split(',')[1]); const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; const ab = new ArrayBuffer(byteString.length); const ia = new Uint8Array(ab); for (let i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } const blob = new Blob([ab], { type: mimeString }); return blob; }</code>
Usage
You can now use dataURItoBlob() to transform your Data URL into a Blob object:
<code class="javascript">const dataURL = 'data:image/png;base64,...'; const blob = dataURItoBlob(dataURL);</code>
The above is the detailed content of How to Convert a Data URL to a Blob in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!