Read file as dataURL

suggest change

Reading 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]);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents