So I need to make a way to import a file and show it on the user's screen. I cannot use PHP, as it is for a chrome extension. I am using the fileReader() API, and am using this to read the binary file. Is there any way to render an image directly from the user?
2 Answers
Skip the FileReader part. Take the File or Blob you're reading and create an object URL for it.
img.src = URL.createObjectURL(file);
7 Comments
blob: URL that references the local file data. Use the same file object here as you would have if you were using the FileReader.file in this case?You can use FileReader.readAsDataURL() for images.
Simply read the documentation.
Try it yourself:
const input = document.getElementById('input');
const img = document.getElementById('img');
const reader = new FileReader();
reader.addEventListener('load', showImage);
input.addEventListener('change', readImage);
function readImage(){
if (!this.files) return;
reader.readAsDataURL(this.files[0]);
}
function showImage(){
img.src = this.result;
}
<input id="input" type="file" onchange="showImage()">
<img id="img">
Read more about FileReader API.
EDIT - for future readers
It's unfair to judge FileReader.readAsDataURL() by only one argument, that it is "horribly inefficient". After all, if it is in the standard spec, it serves its own purpose.
While FileReader.readAsDataURL() is indeed less efficient than URL.createObjectURL() in this case, there is a difference:
.readAsDataURLis asynchronous,.createObjectURL()is not..readAsDataURLcan be garbage collected automatically,.createObjectURLcannot.
But of course, these difference can be trivial, depending on your apps' implementation and application.