Home > Net >  How to encode an <input type="file> as a base64 string?
How to encode an <input type="file> as a base64 string?

Time:10-27

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?

CodePudding user response:

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 onl oad 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;

CodePudding user response:

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.

document.getElementById("image").files;

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.name = file.name;
    fileInfo.size = file.size;
    fileInfo.extension = file.name.split(".")[file.name.split(".").length - 1];

    console.log(r.target.result.split("base64,")[1]);
};
reader.onerror = function () {
    throw new Error(`unknown error while converting file to ${defaultOptions.dataType}`);
};

reader.readAsDataURL(file);
  • Related