10

How To Read and Process Files with the JavaScript FileReader API

 3 years ago
source link: https://www.digitalocean.com/community/tutorials/js-file-reader
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Tutorial

How To Read and Process Files with the JavaScript FileReader API

JavaScript

  • By Jack Misteli

    Last Validated onApril 22, 2021 Originally Published onJanuary 23, 2020 31.5k views

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK