Learn how to use Dash Bio for next-gen sequencing & quality control. 🧬Register for the Oct 27 webinar.

toImage and reading the base64 in node.js

I’m trying to save my image I created using Plotly.js on the client-side to a folder location on my server. I’m using toImage to convert the data to a base64 url, but I can’t seem to get the file to read into a viewable picture afterward. Help?

Client-side code:

//get the div and create the base64 url

graphdiv = document.getElementById(‘graphdivID’)
try{
var url = await Plotly.toImage(graphdiv, {format:‘jpeg’, height: 500, width: 500 })
} catch (err) {
console.log(err)
}

//set options to post it to the server

const options = {
method: ‘POST’,
headers: {
‘Content-type’: ‘application/json’
},
body: JSON.stringify(url)
};

//post the request to the server

const response = await fetch(’/saveimage’, options);

Server side:

router.post("/saveimage", (req, res) => {
const fs = require(‘fs’)
fs.writeFile(“testing.jpeg”, Buffer.from(req.body.url, “base64”), function(err) {});
});

Using this, the file is written, but when I go to open it, it’s unreadable - blank. Am I going about this the wrong way? Is there an easier way to recreate and save the image using the plotly package in node? Any help would be greatly appreciated

Do you get any error if you add a log in function(err) {}?

I don’t know. I ended up passing the plot variables (data,layout,config) via JSON, and then used the Node.js docs to stream the file.

Continuously similar concerns, I have you discovered an answer I took a stab at everything it actually doesn’t work.

If any suggestion please reply.

Did you ever find a solution for this? I’m in the same situation.