Solution 1 :

You need to load the image into a temporary img element and then you can convert it to base64 when the temporary element has loaded the image.

Use the image as img.src = (YourImageSource)

From the onload function you can then retrieve the base64 value.

var imgEl = document.createElement('img');
imgEl.onload = function(){
    var canvas = document.createElement('canvas');
    canvas.width = this.width;
    canvas.height = this.height;
    var ctx = canvas.getContext('2d');
    const d = canvas.toDataURL('image/jpeg');
imgEl.src = img;

Solution 2 :

Run below code, if you already upload your file then the console will show the base64 of the file
The example is for only first file.
If you need upload more than one files. You can loop to make it.


Using files array to get each file’s base64.

var file = document.getElementById("image").files[0];
var reader = new FileReader();

reader.onload = function (r) {
    var fileInfo = new Object(); =;
    fileInfo.size = file.size;
    fileInfo.extension =".")[".").length - 1];

reader.onerror = function (ex) {


Problem :

I am trying to send an image to my express backend. I have tried adding the image directly to my post request body.

var imgValue = document.getElementById("image").value; 

In my post request

body : JSON.stringify({

Accessing the image on the backend only gives me the name of the file. Is there any way I can encode the image as a base64 string in the frontend itself?


Comment posted by Evert

Why do this at all? It’s terribly inefficient.

Comment posted by RaptorRV

@Evert I am kind of newbie at this. This is a way I thought of. Are there more efficient ways of doing the same ?

Comment posted by RaptorRV

I implemented one of the solutions below, and yes, it is quite inefficient.

Comment posted by Evert

Send the file as a binary, or using the multipart format