Read file as dataURL
suggest changeReading the contents of a file within a web application can be accomplished by utilizing the HTML5 File API. First, add an input with type="file" in your HTML:
<input type="file" id="upload">
FileReader is a browser API. Add a change listener on the file input. It runs each time a new file is selected. readAsDataURL produces a data: URL. The image’s load handler runs only if the browser can decode that file as an image:
document.getElementById('upload').addEventListener('change', showImage);
function showImage(evt) {
const files = evt.target.files;
if (files.length === 0) {
console.log('No files selected');
return;
}
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
document.body.appendChild(img);
};
img.src = event.target.result;
};
reader.readAsDataURL(files[0]);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents