Convert a File URL/File to a Base64 string or DataURL using JavaScript

Sh Raj - Jan 16 '22 - - Dev Community

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

That’s it! - Source

Now It's Time to convert a URL file to Base64

Let's we have an Image Here :- https://Gurimg.sh20raj.repl.co/logo.jpg

Here is the Function...

function toDataUrl(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        var reader = new FileReader();
        reader.onloadend = function() {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
}
Enter fullscreen mode Exit fullscreen mode

Here is the function you have to run and get the image base64 on your console.

toDataUrl("https://Gurimg.sh20raj.repl.co/logo.jpg", function(myBase64) {
    console.log(myBase64); // myBase64 is the base64 string
});
Enter fullscreen mode Exit fullscreen mode

Checkout Instagram :-


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .