File, Blob, ArrayBuffer

yahone chow
2 min readMay 26, 2020

To start All of this, you need get a raw-data of any files.

Suppose you have a PNG file.

We can get its raw data by HEX-readers or just javascript.

BinEd on WebStorm
// html
<input type="file" id="file1" />
// js

file1.files[0].arrayBuffer().then(resp=>{
let ui8 = new Uint8Array(resp);
let rawData = [...ui8];
})

Now we get raw data of 2.png here

rawData = [137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,30,0,0,0,30,8,6,0,0,0,59,48,174,162,0,0,0,220,73,68,65,84,72,199,237,214,81,14,194,32,12,0,80,60,128,215,219,49,28,91,118,10,55,216,53,188,132,137,39,19,71,130,75,69,42,148,194,76,116,31,253,89,40,111,233,104,153,48,198,136,111,132,216,225,255,134,143,151,166,84,28,150,152,151,24,158,207,182,130,45,106,92,12,91,193,16,93,241,218,112,8,181,113,174,9,163,232,90,234,130,223,50,134,142,47,135,11,36,216,183,57,49,81,29,67,125,120,116,11,238,12,60,9,133,240,228,45,180,120,91,11,133,112,31,72,176,184,100,162,19,150,3,75,157,139,147,209,208,225,234,136,184,202,65,177,118,146,200,102,178,20,250,169,143,49,188,43,129,198,6,136,116,101,246,55,191,33,168,162,116,65,108,114,97,56,11,77,29,153,109,4,87,57,195,38,117,86,95,75,162,20,56,84,114,205,153,233,148,219,9,226,154,123,131,81,175,69,201,41,239,27,188,255,222,254,52,252,0,234,253,186,89,222,225,73,252,0,0,0,0,73,69,78,68,174,66,96,130]

Since a Blob consists of ArrayBuffer and something else, you can create a Blob from TypedArray raw data.

let blob1 = new Blob([new Uint8Array(rawData)],{type:'image/png'})

Showing a PNG blob on page

DOM.insertAdjacentHTML(
'beforebegin',
'<img id="img1" src="' + URL.createObjectURL(blob1) + '" />'
);

Or download it as a file

let aDom = document.createElement('a')

if('download' in aDom){
aDom.type = 'download'
aDom.href = URL.createObjectURL(blob1)
aDom.download = '2.png'
aDom.click()
}

Or create a file from a blob

let fileA = new File([blob1],{type:'image/png'})

Convert to base64

let reader = new FileReader();
reader.readAsDataURL(blob1)
reader.onload = () => {
let base64 = 'data:image/png;base64,' + reader.result.replace(/^data:.+;base64,/, '');
console.log(base64);
};

ArrayBuffer

array buffer Usage

--

--