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 = () => {
            console.log(reader.result);
            // Logs data:<type>;base64,wL2dvYWwgbW9yZ...
        };
        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(/^.+,/, '');

            console.log(base64String);
            // Logs wL2dvYWwgbW9yZ...
        };
        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!

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

Or join my newsletter

More articles More articles