Read a File into JavaScript using FileReader

OpenJavaScript 0

Last updated: December 15, 2022.

You can read ordinary files into JavaScript with help from the FileReader object constructor. This object can be used to set up a new file reader.

A file reader can accept two types of object: File (created automatically when user selects a file) or Blob. A Blob is more common when the file is a fetched resource.

Let’s start with a little markup so its possible to select a local file:

<body>

    <input type="file">
    <div id="preview"></div>
    
</body>

You can now start reading the selected file when one is selected by listening for a change event on the file input element and creating a new FileReader instance.

Now, select a format to read the file to. You can:

  • readAsDataURL: Encodes to Base-64 string that functions as a URL
  • readAsText: Reads as plain text
  • readAsArrayBuffer: Outputs an ArrayBuffer object

In the below example, a selected file will be read using the readAsDataURL method. This method is quite powerful because it allows you to string-encode any type of file.

This can be useful for posting data as part of a stringified payload (e.g. with other form data). It also allows you to pass any file through local storage / session storage.

const fileInput = document.querySelector('[type="file"]');
const preview = document.getElementById('preview');

fileInput.addEventListener('change', () => {
// This function runs when file is selected

    const fr = new FileReader(); 
    // Creates new FileReader instance

    fr.readAsDataURL(fileInput.files[0]);
    // Reads user-selected file (other reading methods possible)
    
    fr.addEventListener('load', () => {
        // This function runs when reading is complete
        
        const url = fr.result;
        // Result always available on result property on the file reader

        console.log(url); 
        // data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA14AAAOaCA... (very long!)
        
    })

});

You can also create client-side apps that will edit and then output files as a URL (e.g. to set an image element), post to a server or return to the user as a client-side download.

For example, the code below reads an image and outputs a data URL. This is then set as the src of an Image element and, when the image has loaded, converted to grayscale using the HTML Canvas API:

const fileInput = document.querySelector('[type="file"]');
const preview = document.getElementById('preview');

fileInput.addEventListener('change', () => {

    const fr = new FileReader();

    fr.readAsDataURL(fileInput.files[0]);
    
    fr.addEventListener('load', () => {

        const url = fr.result;
        
        const img = new Image();
        img.src = url;
        // Sets data URL to image src

        img.onload = () => {
            // This function runs when image has loaded

            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            // Creates new 2D canvas element

            canvas.width = img.width;
            canvas.height = img.height;
            // Sets height and width of canvas to image dimensions

            ctx.filter = 'grayscale(1)';
            ctx.drawImage(img, 0, 0);
            // Apply grayscale filter to canvas and draw image

            preview.appendChild(canvas);
            // Display editied image in canvas

        }
        
    })

});

Happy (file) reading!

Related posts