Wednesday, November 2, 2022

[FIXED] How to encode an <input type="file> as a base64 string?

Issue

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({
image:imgValue
})

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?


Solution

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');
    ctx.drawImage(this,0,0);
    const d = canvas.toDataURL('image/jpeg');
    console.log('base64',d);
};
imgEl.src = img;



Answered By - HendrikThurauEnterprises
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.