Filereader Readasdataurl Creating Large Base64 Images
Solution 1:
I have 5,882,455 bytes for the FileReader vs 5,882,433 bytes for base64
output, if you add the 22 bytes from data:image/png;base64,
, we're not too far.
However to the question How can i make this more efficient?, just don't use a data URL here. Whatever you've been told you need it too, it was a lie (I'm 99% percent sure).
Instead you should always prefer to work with the Blob directly.
To display it, use a blob URL:
inp.onchange = e => {
img.src = URL.createObjectURL(inp.files[0]);
};
<inputtype="file"id="inp"><imgid="img"src=""height="200"alt="Image preview..."accept="image/*">
To send it to your server, send the Blob directly, either through a FormData or, directly from xhr.send() or as the body of a fetch request.
The only case can think of where you would need a data URL version of a binary file on the front end is to generate a standalone document which would need to embed that binary file. For all other use cases I met in my career, Blob where far better suited.
For the message that gets printed in the Chrome's tooltip, that's the size of the USVString that the browser has to hold in memory. It's twice the size of the file you have on disk, because USVStrings are encoded in UTF-16, even though this string holds only ASCII characters. However, to be sent to your server, or to be saved as a text file, it will generally be reencoded in an 8 bit encoding, and retrieve it's normal size.
So don't take this tooltip as a mean to tell you how big your data is, it's only the size it does take in the browser's allocated memory, but outside, it won't be the same at all.
If you wanna check the size of binary data generated here is a better fiddle, which will convert USVStrings to UTF-8 and keep binary as binary (e.g if you pass an ArrayBuffer to it):
functionpreviewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = newFileReader();
reader.addEventListener("load", function () {
console.log(newBlob([reader.result]).size);
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL --><inputtype="file"onchange="previewFile()"><br><imgsrc=""height="200"alt="Image preview...">
Post a Comment for "Filereader Readasdataurl Creating Large Base64 Images"