简体   繁体   中英

Save canvas dataurl to user's file system

Okay, so, I have a MVC app where I'm creating a canvas image, and getting the data url just by doing canvas.toDataURL("image/png"). What I'd like to do is save this to the user's file system.

I tried doing it just with javascript by doing:

var saveUrl = canvas.toDataURL("image/png");
saveUrl = saveUrl.replace("image/png", "application/octet");
window.open(saveUrl);

But that just gives me a file named download without any extension or anything. I'd like to get the save dialog and give the file a type and name, and save that to the user's disc.

So I figured I could post the data to the server, and then do something with the response headers to tell the browser that I'm trying to save an image for it, but I can't find a good way to do this. I'm using ASP.NET MVC. Does anyone have a good easy way for me to do this?

Here's what I ended up with:

Post image:

[HttpPost]
public void PostImageForPrinting(string dataUrl)
{
    SomePersistentObject.CurrentDataURL = dataUrl;
}

Serve Image:

public ActionResult PrintMission()
{
    var url =
            SomePersistentObject.CurrentDataURL.Substring(SomePersistentObject.CurrentDataURL.IndexOf(",") + 1);
    var image = Convert.FromBase64String(url);
    return base.File(image, "image/png", "mission.png");
}

Client side:

var saveUrl = canvas.toDataURL("image/png");
var jsonString = JSON.stringify({ dataUrl: saveUrl });
$.ajax({
    url: "/Home/PostImageForPrinting",
    contentType: "application/json",
    type: "POST",
    data: jsonString,
    success: function (result) {
        window.location.href = "/Home/PrintMission";
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM