Convert a File URL/File to a Base64 string or DataURL using JavaScript
Tags: javascript, tutorial, sh20raj, tips
Published: 2022-01-16 05:32:54

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.

```html
<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.

```HTml
<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.

```html
<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.

```javascript
URL.revokeObjectURL(fileUrl);
```
That’s it! - [Source](https://pqina.nl/blog/convert-a-file-to-a-base64-string-with-javascript/)

## 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...
```javascript
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();
}
```

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

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

> Checkout Instagram :-
> {% instagram CYKELXKPJ_r %}