How to save html2canvas image into System Folder in jquery

送分小仙女□ 提交于 2019-12-04 11:05:15

System hardisk? I did not understand, server or client?

CLIENT

If you want the user to download the image automatically, you will need to modify the Data URI scheme

Try this:

Add in css

#myHideFrame {
    position: absolute;
    top: -9999px;
    width: 1px;
    height: 1px;
}

Add in Javascript

var img = canvas.toDataURL();
var frame = document.getElementById("myHideFrame");
if(!frame) {
    frame = document.createElement("iframe");
    frame.id = "myHideFrame";
    document.body.appendChild(frame);
}
frame.src = img.replace(/^data[:]image\/(png|jpg|jpeg)[;]/i, "data:application/octet-stream;");

Unfortunately this example does not show the name, for this you will have to do something like this (user need click in link):

var img = canvas.toDataURL();
var link = document.createElement("a");
link.download = "photo.png"; //Setup name file
link.href = img.replace(/^data[:]image\/(png|jpg|jpeg)[;]/i, "data:application/octet-stream;");
document.body.appendChild(link);

SERVER

If you want to save on the server then you need to use Ajax, example with Jquery:

Javascript file:

var img = canvas.toDataURL().replace(/^data[:]image\/(png|jpg|jpeg)[;]base64,/i, "");
$.ajax({
    "type": "POST",
    "url": "upload.aspx/UploadImage",
    "data": { 
        "imageData": img //Send to WebMethod
    }
}).done(function(o) {
    console.log(["Response:" , o]); 
});

Your upload.aspx.cs file need:

...
[WebMethod()]
public static void UploadImage(string imageData)
{
    string fileNameWitPath = "custom_name.png";
    using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            byte[] data = Convert.FromBase64String(imageData);//convert from base64
            bw.Write(data);
            bw.Close();
        }
    }
}
...

See details: http://www.dotnetfunda.com/articles/show/1662/saving-html-5-canvas-as-image-on-the-server-using-aspnet

A much simpler solution to save an image on the Client side will be to generate an image data and append it to the <a> tag with download attribute on it.

Here is my example:

HTML:

<a href="#" class="downloadAsImage hide" download>Download</a>

JS:

$(function() {
    html2canvas($('.main'), {
        onrendered: function(canvas) {
            $('.downloadAsImage').attr('href', canvas.toDataURL()).removeClass('hide');
        }
    });
});

Side note: bare in mind that you can't click $('.downloadAsImage') via JS as it has download attribute on it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!