The File API lets web pages access user files (with the user’s consent). The user can upload files using an input element or by dragging and dropping the file into a specific area of the page. Then, you can use the File object to access the file and its contents.

If you use an <input type="file"> HTML element, you can get the uploaded files with the files property. That property is not an array-like object because it’s possible to upload multiple files to the same input.

If we have this input: <input type="file" id="fileInput">, this is how we can access the file:

const fileInput = document.querySelector("#fileInput");
console.log(fileInput.files[0]);
// 👆 prints the file object

If you upload multiple files, you will access the other files by using files[1], files[2], etc. And if the user didn’t upload anything, the property files[0] will not exist (i.e. it will be undefined). Each one of these is a File object.

To read the file contents, You have the text() asynchronous method, you can use it to get the raw contents as text. It’s very useful if the user uploads a plain text file.

For example, if you uploaded a file called “test.txt” with the contents “Hello, my name is Nico”, this is what you can read the file with JavaScript:

async function readFile() {
    const fileInput = document.querySelector("#fileInput");
    if (fileInput.files[0]) { // If the file was uploaded
        const fileContents = await fileInput.files[0].text();

        alert(fileContents);
    }
}

Handling Images

With images, you can even display the uploaded image to the user. FileReader objects let you create a special URL with the image contents, and you can pass that URL to an <img> element. This is how you use it:

async function readFile() {
    const fileInput = document.querySelector("#fileInput");
    const image = document.querySelector("#previewImage"); // <img> element

    if (fileInput.files[0]) { // If the file was uploaded
        const fileReader = new FileReader();
        fileReader.readAsDataURL(fileInput.files[0]);

        fileReader.onload = function(event) {
            const imageDataURL = event.target.result; // The Data URL
            image.setAttribute("src", imageDataURL);
        }
    }
}

The file reader has the readAsDataURL method. However, you have to handle the load event to the reader. When this event is triggered, you can get the data URL and pass it to the image.