Using JavaScript to Convert a File to a Base64 String or DataURL

Converting JavaScript file objects to base64 strings can be useful, for example for when you can only send string based data to your server. In this tutorial we will explore how to generate a base64 string and how to create a Data URL.

If you want to convert a JavaScript file object to a base64 string you can either opt to use Doka with FilePond and its File Encode plugin or use one of the code snippets below.

Encoding the file as a DataURL

This snippet creates a Data URL which can be used as a src for an image tag <img src="..."> or as a value for background-image: url(...)

Doka.create({
    onconfirm: output => {
        // get a reference to the file
        const file = output.file;

        // encode the file using the FileReader API
        const reader = new FileReader();
        reader.onloadend = () => {

            // log to console
            console.log(reader.result) // logs data:image/jpeg;base64,wL2dvYWwgbW9yZ...

        };
        reader.readAsDataURL(file);
    }
})

Encoding the file as a Base64 String

This snippet creates a base64 string, it's similar to the previous example but it uses a regular expression to remove the Data URL part.

Doka.create({
    onconfirm: output => {
        // get a reference to the file
        const file = output.file;

        // 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
            console.log(base64String) // logs wL2dvYWwgbW9yZ...

        };
        reader.readAsDataURL(file);
    }
})

Generating a URL 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 an <img> src attribute? The URL.createObjectURL() method can help here.

The following code snippet will return a URL to our file object.

const fileURL = URL.createObjectURL(myFileObject);
img.src = fileURL;

If we no longer need the URL we can remove it using:

URL.revokeObjectURL(fileUrl);