Here's the simple code:
document.querySelector('#upload').addEventListener('change', async (e) => {
const initialFile = e.target.files[0];
const arrayBuffer = await initialFile.arrayBuffer();
const text = await initialFile.text();
var enc = new TextEncoder();
const arrayBufferFromText = enc.encode(text).buffer
// WHY THESE TWO AREN'T THE SAME?
console.log(arrayBuffer.byteLength)
console.log(arrayBufferFromText.byteLength);
})
<input type="file" id="upload">
When uploading a binary file, e.g. an image, arrayBuffer
will be different from arrayBufferFromText
. That's apparently happening somewhere in the text -> buffer conversion using TextEncoder
.
Why is this happening and how to get arrayBufferFromText
the same as arrayBuffer
?