Tutorial

How To Read and Process Files with the JavaScript FileReader API

Updated on April 22, 2021
author

Jack Misteli

How To Read and Process Files with the JavaScript FileReader API

Introduction

Web browsers that support FileReader and <input type="file"> allow users to upload files.

In this article, you will explore the File, FileReader, and FileReaderSync APIs.

Prerequisites

If you would like to follow along with this article, you will need:

  • An understanding of JavaScript methods, EventListener, and Promises will be helpful.
  • A code editor.
  • A modern web browser that supports File, FileReader, and FileReaderSync.

Uploading a File

First, to get a file from a user, we need to use an <input> element:

<input id="input" type="file" />

This code will let users upload files from their machines.

Here’s an example of uploading a file using an HTML <form>:

<form enctype="multipart/form-data" action="/upload" method="post">
  <input id="input" type="file" />
</form>

For greater control in handling uploads, you can use JavaScript instead of an HTML <form> to submit the files:

let file = document.getElementById('input').files[0];
let formData = new FormData();

formData.append('file', file);
fetch('/upload/image', {method: "POST", body: formData});

This approach uses FormData and fetch.

Using File Blob Properties

In modern browsers, Files have Blob properties and functions. These functions allows us to read the file.

  • .text() transforms the file into a stream and then into a string.
  • .stream() returns a ReadableStream.
  • .arrayBuffer() returns an ArrayBuffer that contains the blob’s data in binary form.
  • .slice() allows you to get slices of the file.

Create a new myFile.txt file with some text:

myFile.txt
Example file content.

Then, create a new file-blob-example.html file:

file-blob-example.html
<!DOCTYPE html>
<html>
<body>
  <input type="file" id="input" />

  <script>
    const streamToText = async (blob) => {
      const readableStream = await blob.getReader();
      const chunk = await readableStream.read();

      return new TextDecoder('utf-8').decode(chunk.value);
    };

    const bufferToText = (buffer) => {
      const bufferByteLength = buffer.byteLength;
      const bufferUint8Array = new Uint8Array(buffer, 0, bufferByteLength);

      return new TextDecoder().decode(bufferUint8Array);
    };

    document.getElementById('input').addEventListener('change', function(e) {
      let file = document.getElementById('input').files[0];

      (async () => {
        const fileContent = await file.text();

        console.log('.text()', fileContent);

        const fileContentStream = await file.stream();

        console.log('.stream()', await streamToText(fileContentStream));

        const buffer = await file.arrayBuffer();

        console.log('.buffer()', bufferToText(buffer));

        const fileSliceBlob = file.slice(0, file.length);
        const fileSliceBlobStream = await fileSliceBlob.stream();

        console.log('.slice() and .stream()', await streamToText(fileSliceBlobStream));
      })();
    });
  </script>
</body>
</html>

Open file-blob-example.html in your web browser and add the myFile.txt file to the input. In your web developer console, you will see the file contents read out using .text(), .stream(), .buffer(), and .slice().

This approach uses ReadableStream, TextDecoder(), and Uint8Array().

Applying FileReader Lifecycle and Methods

There are 6 main events attached to FileReader:

  • loadstart: Fires when we start loading a file.
  • progress: Fires when the blob is read in memory.
  • abort: Fires when we call .abort.
  • error: Fires when an error occurs.
  • load: Fires when the read is successful.
  • loadend: Fires when the file is loaded and if error or abort didn’t get called or if load starts a new read.

To start loading our file we have four methods:

  • readAsArrayBuffer(file): Reads the file or blob as an array buffer. One use case is to send large files to a service worker.
  • readAsBinaryString(file): Reads the file as a binary string
  • readAsText(file, format): Reads the file as USVString (almost like a string), and you can specify an optional format.
  • readAsDataURL(file): This will return a URL where you can access the file’s content, it is Base64 encoded and ready to send to your server

Create a new filereader-example.html file that uses readAsDataURL():

filereader-example.html
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background: #000;
      color: white;
    }

    #progress-bar {
      margin-top: 1em;
      width: 100vw;
      height: 1em;
      background: red;
      transition: 0.3s;
    }
  </style>
</head>
<body>
  <input type="file" id="input" />
  <progress value="0" max="100" id="progress-bar"></progress>
  <div id="status"></div>
  <script>
    const changeStatus = (status) => {
      document.getElementById('status').innerHTML = status;
    }

    const setProgress = (e) => {
      const fr = e.target;
      const loadingPercentage = 100 * e.loaded / e.total;

      document.getElementById('progress-bar').value = loadingPercentage;
    }

    const loaded = (e) => {
      const fr = e.target;
      var result = fr.result;

      changeStatus('Finished Loading!');
      console.log('Result:', result);
    }

    const errorHandler = (e) => {
      changeStatus('Error: ' + e.target.error.name);
    }

    const processFile = (file) => {
      const fr = new FileReader();

      fr.readAsDataURL(file);
      fr.addEventListener('loadstart', changeStatus('Start Loading'));
      fr.addEventListener('load', changeStatus('Loaded'));
      fr.addEventListener('loadend', loaded);
      fr.addEventListener('progress', setProgress);
      fr.addEventListener('error', errorHandler);
      fr.addEventListener('abort', changeStatus('Interrupted'));
    }

    document.getElementById('input').addEventListener('change', (e) => {
      const file = document.getElementById('input').files[0];

      if (file) {
        processFile(file);
      }
    });
  </script>
</body>
</html>

Open filereader-example.html in your web browser and add the myFile.txt file to the input. A progress bar will appear on the screen as the file is processed. If it loads successfully, it will indicate 'Start Loading', 'Loaded', and 'Finished Loading'.

Using FileReaderSync

FileReader is an asynchronous API because we do not want to block the main thread while reading files. For example, we don’t want our user interface to stop working when the browser is trying to read a very large file. However, there is a synchronous version of FileReader called FileReaderSync. We can only use FileReaderSync in Web Workers. Web workers have their own thread so they won’t block the main thread. FileReaderSync uses the same methods as FileReader:

  • FileReaderSync.readAsArrayBuffer()
  • FileReaderSync.readAsBinaryString()
  • FileReaderSync.readAsText()
  • FileReaderSync.readAsDataURL()

There are no event handlers because it’s synchronous.

Conclusion

In this article, you explored the File, FileReader, and FileReaderSync APIs.

Take the time to check the browser support for these features to ensure that they are applicable to the users of your projects.

Continue your learning with additional Web APIs.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Jack Misteli

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.