Search code examples
javascriptjqueryhtmlcanvasfileserver

Append div content as an image to formData using Javascript


I have a div which the content is filled dynamically from the server and plot some bar chart, after which I am try to get this same div and append it to form data so to save it as an image on the server. The first part work perfectly (plotting the chart). The second part which I've tried with the code below only upload an empty PNG file with no content of chart.

 $("#myChart").get(0).toBlob(function(blob) {
                    var image = blob;
                    var forms = document.querySelector('form#chartData');
                    var request = new XMLHttpRequest();
                    var formDatas = new FormData(forms);
                    formDatas.append('chartImage', blob, "chart.png");
                    request.open('post','/sendToServer');
                    request.send(formDatas);
                    request.onreadystatechange = function() {
                        if (request.readyState === 4) {
                            if (request.status === 200) {

                                /*File Uploaded*/

                            }
                        }
                    }
                });

However when I use saveAs(blob, "chart_1.png") the image is downloaded successfully with chart well plotted. I don't know if I am missing out something. Any help is appreciated. I am using FileSaver.js and canvas-toBlob.js


Solution

  • Ok for sake of those that might be facing the same issue, this is what I ended up doing and it works fine:

     html2canvas([document.getElementById('myChart')], {
                            onrendered: function (canvas) {
                                var imagedata = canvas.toDataURL('image/png');
                                var imgdata = imagedata.replace(/^data:image\/(png|jpg);base64,/, "");
                                console.log(imgdata);
            //ajax call to save image inside folder
            $.ajax({
                url: '/sendToServer',
                data: {
                 chartImage:imgdata
             },
             type: 'post',
             success: function (response) {   
                 console.log(response);
                   //$('#image_id img').attr('src', response);
               }
           });
        }
    });
    

    Then PHP script to handle the upload

    $imagedata = base64_decode($_POST['imgdata']);
            $filename = md5(uniqid(rand(), true));
            $file = $_SERVER['DOCUMENT_ROOT'] . '/images/'.$filename.'.png';
            $imageurl  = 'http://127.0.0.1'.$filename.'.png';
            file_put_contents($file,$imagedata);
            return $file;
    

    Note: html2canvas.js required.

    Sample image I uploaded is attached.enter image description here