Andrew Kim
Andrew Kim's Blog

Andrew Kim's Blog

A JS code snippet - reading a file element as blob

Andrew Kim's photo
Andrew Kim
·Dec 16, 2021·

1 min read

Occasionally there is a need to handle and process a binary file on the web browser, then there is a need to read files as blob.

This is a short code snippet to accomplish just that.

const uploadedFile = document.getElementById('file-elem');
const reader = new FileReader();
reader.onload = function(event) {
    let blob = new Blob([new Uint8Array(event.target.result)], { type: uploadedFile.type });
    console.log(blob);
}
reader.readAsArrayBuffer(uploadedFile.files[0]);

Then the output goes something like this:

Blob {size: 1736645, type: 'file'}
 
Share this