how to convert canvas element to a buffer and a base64 so server can send to mongoDB?

  base64, canvas, javascript, node.js

Objective: After converting two canvas elements as a data url, I am sending it to my server, so I can create a new buffer from a base 64. Then i’m going to convert the two buffers back to a base64 and send both buffers and base64 strings to my mongoDB.

Background:

  1. I am sending leftsidestate and rightsidestate to my server
constructor(props) {
        super(props)

        this.myRef = React.createRef();
        this.pref = React.createRef();
        this.secondmyRef = React.createRef();
        this.state = {
            isFlipped: false,
            happy: HAPPINESS,
            leftsidestate: { //sending this to my server
                imgstring1: '' 
            },
            rightsidestate: { //sending this to my server
                imgstring2: ''
            },
            dogpic: null,
            newdog: null

        }
        this.updateCanvas = this.updateCanvas.bind(this);
        this.updateCanvas2 = this.updateCanvas2.bind(this);
        // this.convertfirstcanvastoimage = this.convertfirstcanvastoimage.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);

    }
  1. in my handleSubmit I am converting my canvas elements to dataURLs and trimming them and sending it to my server. I am not sure the correct way to trim them but they both give me similar results…
handleSubmit(event) {
        event.preventDefault()

        const canvas = this.myRef.current;
        const imgUrl = canvas.toDataURL();
        const trimmedURl = imgUrl.split(';base64,')[1];
        // console.log("trimmed url is", trimmedURl);
        let leftsidestate = this.state.leftsidestate;
        leftsidestate.imgstring1 = trimmedURl;
        this.setState({ leftsidestate: leftsidestate

        });
        console.log("left side state is ", this.state.leftsidestate)  

        const canvas2 = this.secondmyRef.current;
        const imgUrl2 = canvas2.toDataURL();
        const trimmedURl2 = imgUrl2.split(",")[1]
        // console.log("trimmed url2 is", trimmedURl2);
        let rightsidestate = this.state.rightsidestate;
        rightsidestate.imgstring2 = trimmedURl2;
        this.setState({ rightsidestate: rightsidestate

        });
        console.log("right side state is ", this.state.rightsidestate)
  
        const imgs = {
            leftsidestate,
            rightsidestate
        };

      const data = this.state.leftsidestate;

      fetch( 'http://localhost:9000/create', {
        method: "POST",
        headers: {
            'Content-type': 'application/json'
        },
        body: JSON.stringify(imgs)
        })
        .then((response) => response.json())
        .then((result) => {
            console.log(result)
        })
  

       
    }

leftsidestate and rightsidestate imgstrings after DataURl and trimming them.

left side state is  {imgstring1: "iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAgAE…r2Ecv28dBuxXH/V6MDvrx/+44U1UZtWeZAAAAAElFTkSuQmCC"}
right side state is  {imgstring2: "iVBORw0KGgoAAAANSUhEUgAABhIAAAPpCAYAAADwxrdTAAAgAE…BAgQIECBAgAABAgQIEMgIDPDFttIVFDqyAAAAAElFTkSuQmCC"}

server-side:

app.post('/create', function(req, res) {
  console.log("does something")
  var imgstring = req.body.leftsidestate;
  var imgstring2 = req.body.rightsidestate;
  console.log("image string is " , imgstring);
  console.log("image string2 is " , imgstring2);

  
  //buffer stores raw data (raw memory)

  var image = Buffer.from(imgstring, 'base64'); //stops at this line
  console.log("does this statement reach first");
  console.log("image is " + image);

  var newimage = image.toString('base64');
  console.log("does this statement reach");

  console.log("image is", image);
  console.log("new image is", newimage);

  var image2 = Buffer.from(imgstring2, "base64");
  var newimage2 = image2.toString('base64');
  console.log("image2 is" + image2);
  console.log("new image2 is" + newimage2);

});

issue:

1)var image = buffer.from(imgstring, 'base64') i get a 500 internal server error

2)inside imgstring1 and imgstring2, i get a super long string that looks wrong. both string print out something similar to:

BtwD5k6bEIohztw3/VGxVBcLBVFpqxc9Ab/nt1fQMHUwarxc4PQjITqRDXRRGT/9T/+SW3bmEoBEzxcgO5NwbpXsMt4InVbyYZGbOMkgZFUgbAACp0kOaY5CNhNnCx+VUvJm6YAJqKmaQMUFoDAhC+psCfTvxS7pTeiouXVuKU0LmhbdY/pn7mMnHIqfoD5bEg82m3bbslTcmz61V2XmlORT/la64RrubPST4oVFxktOK07qTXdQRx3RrFf9OMPX/w8TndOI29heNbzNYQ7wweGSfq9myQ4oP3dGfUAKJ0EjJGbbWgWSzos5vetOixuDIrT3e2NCJxtvChlJXxrI7ukUePDxUCQFBceZLXrPDQ6yVcqNjwsfD8Z8a0sV6HA7u7ux6C/oxvo9uZOKTJgYIdH+8oDlF4UVf6uyZec8tL9rRb6cxQkOSfg5xSOzWKjKFyrrmWR0+gKlfQdtexz6NgA3lnSkOrM6yPIgU6djSMdIj7fUDY4fTkoSIQ+PT5VgOv11Y0efpYAHHA//elPVZh4LSwaREvQQwir3Gk249FQfLDmEEVSxAio6PSGxMpDCiGPA3uzVjGH2U5Twj/zUMtBgg6OJQL2Nou5wl2lCRQtgmJJJqQ/g3xnpMWUMvygoxB4kgo7YzjjPK+BE5s/w/flM4J8yv1BETOvEbpCOzZ7w7jabuP9fBXLTj/qfBjDnVHk/U60+lls822ss3VsKndp6ookFHZWw70FuHnt9upK04OI32CwSTjfjLEc1ljcECWP7pWgjoxEnBJpmSkSbKyVWMUmTck/CadKdk52Em5yHnjePHoa/UmdH

and it goes on for quite a white but eventually makes a stop

final notes: why do I have to create an image buffer as well as a base64 string and send those to my mongoDB server? why not just the base64 string? I have seen a couple posts do this, but I do not fully understand why

Source: Ask Javascript Questions

LEAVE A COMMENT