PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

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

 November 02, 2022     express, file, html, javascript, node.js     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing