Convert a File to a Base64 string or DataURL using JavaScript

Converting JavaScript file objects or blobs to Base64 strings can be useful. For example when we can only send string based data to the server. In this tutorial we’ll explore how to use JavaScript to generate a Base64 string and a DataURL from a file object.

In both examples we’ll use a file obtained from a file input field.

Encoding a File as a DataURL

We use FileReader to convert the file object to a dataUR this is done by using the readAsDataURL method.

<input type="file" />

<script>
  // get a reference to the file input
  const fileInput = document.querySelector("input");

  // listen for the change event so we can capture the file
  fileInput.addEventListener("change", (e) => {
    // get a reference to the file
    const file = e.target.files[0];

    // encode the file using the FileReader API
    const reader = new FileReader();
    reader.onloadend = () => {
      // log to console
      // logs data:<type>;base64,wL2dvYWwgbW9yZ...
      console.log(reader.result);
    };
    reader.readAsDataURL(file);
  });
</script>

Encoding the File as a Base64 string

The snippet below creates a base64 string, it’s identical to the previous example but it uses a regular expression to remove the Data URL part.

<input type="file" />

<script>
  // get a reference to the file input
  const fileInput = document.querySelector("input");

  // listen for the change event so we can capture the file
  fileInput.addEventListener("change", (e) => {
    // get a reference to the file
    const file = e.target.files[0];

    // encode the file using the FileReader API
    const reader = new FileReader();
    reader.onloadend = () => {
      // use a regex to remove data url part
      const base64String = reader.result
        .replace("data:", "")
        .replace(/^.+,/, "");

      // log to console
      // logs wL2dvYWwgbW9yZ...
      console.log(base64String);
    };
    reader.readAsDataURL(file);
  });
</script>

Generating a URL that points to a File object

Sometimes we just want to use an File object as an image source. But how to add the file object to the <img> src attribute?

The URL.createObjectURL() method can help here.

The following code snippet will update the image source to the file that is loaded in the file input.

<input type="file" accept="image/*" />

<img src="" alt="" />

<script>
  // get a reference to the file input
  const imageElement = document.querySelector("img");

  // get a reference to the file input
  const fileInput = document.querySelector("input");

  // listen for the change event so we can capture the file
  fileInput.addEventListener("change", (e) => {
    // get a reference to the file
    const file = e.target.files[0];

    // set file as image source
    imageElement.src = URL.createObjectURL(file);
  });
</script>

We need to make sure to revoke the URL if we no longer need the file. If we don’t this causes memory leaks.

URL.revokeObjectURL(fileUrl);

That’s it!

Rik Schennink

Web enthusiast

to pqina.nl