Search code examples
asp.net-mvcjsonkineticjsfilecontentresult

KineticJS - asp.net MVC - Json save canvas data as a downladable PNG file


My project is asp.net MVC 3, I export the canvas data using the following script:

 $("#savePNG").click(function () {
                stage.toDataURL({
                    callback: function (dataUrl) {
                        dataUrl = dataUrl.replace('data:image/png;base64,', '');
                        $.ajax({
                        type: 'POST',
                        url: "../../Home/UploadImage",
                        data: '{ "imageData" : "' + dataUrl + '" }',
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        success: function(msg) {
                            alert('Image saved successfully !');
                        }
                    });
                }
                });
            });

Controller script:

           public FileContentResult UploadImage(string imageData){
            byte[] data = Convert.FromBase64String(imageData);
                   return File(data, "image/png", "test.png");
        }

It is not working, any suggestions, thanks in advance.


Solution

  • Here is my solution just in case someone is trying to do the same

    In the controller:

       public JsonResult UploadImage(string imageData)
            {
                byte[] data = Convert.FromBase64String(imageData);
                MySession.Current._pngtoPrint = data;
    
                return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            }
    
            public FileContentResult ExportPng()
            {
                byte[] contents =  MySession.Current._pngtoPrint;
                return File(contents, "image/png", "test" + ".png");
            }
    

    In the View:

      stage1.toDataURL({
                        callback: function(dataUrl) {
                            dataUrl = dataUrl.replace('data:image/png;base64,', '');
                            $.ajax({
                                type: 'POST',
                                url: "../../Home/UploadImage",
                                data: '{ "imageData" : "' + dataUrl + '" }',
                                contentType: 'application/json; charset=utf-8',
                                dataType: 'json',
                                success: function(data) {
                                   // alert('Image saved successfully !');
                                    window.location("Home/ExportPng");
                                }
                            });
                        }
                    });