Welcome folks today in this blog post we will be converting base64 data url
to binary & blob file
using uint8array in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a index.html
file and copy paste the following code
index.html
1 2 |
<textarea name="" id="base64" cols="30" rows="10"></textarea> <button id="button">Convert to Blob</button> |
As you can see in the above html code we have the simple textarea
where we are receiving the base64 data url of the file and then we have the button to convert to blob in html. And also we have attached the id
to the textarea element and also we have attached the id to the button.
And now we need to make the script.js
file and copy paste the below javascript code as shown below
script.js
1 2 3 |
document.getElementById('button').onclick = () => { console.log(dataURItoBlob()) } |
As you can see that inside the above javascript code we are attaching the onclick
event listener to the button and inside that we are calling the custom function which is dataURItoBlob()
and now we need to define the function as shown below
1 2 3 4 5 6 7 8 9 10 |
function dataURItoBlob(dataURI) { let base64 = document.getElementById('base64').value console.log(base64) var binary = atob(base64.split(',')[1]); var array = []; for (var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], { type: 'image/jpeg' }); } |
As you can see in the above code we are first of all fetching the base64
code from the textarea and then we are using the split()
method and then we are calling the atob()
method to convert the base64 to binary code and then we are using the for loop inside that we are calling the charCodeAt()
function to get the character code and then we are storing it inside the new array and then we are converting the binary array to the blob object using the Uint8Array() method
And now if you open the web app inside the browser you will see the below result as shown below