简体   繁体   中英

image from Jscript to server without postback using base64

I have a canvas with an image taken from a webcam. I want to send that image to my server while avoiding any postback. (With a postback, it force the client to validate the use of the webcam everytime they save an image and I don't want that. :( )

Here's the Jscript

function sendPicture() {
        event.preventDefault();
        var b64 = document.getElementById("canvas").toDataURL("image/png");
        b64 = b64.replace('data:image/png;base64,', '');
        PageMethods.SaveImage(b64, success, error);
    }

    function success()
    { console.log("hoorah"); }

    function error()
    { console.log("boo"); }

Here's the codebehind which isn't written yet but it doesn't matter since it never reach inside anyways.

[WebMethod]
    public static bool SaveImage(string image)
    {
        return false;

    }

The code never reach the WebMethod because the b64 is way too long. (Over 2000 characters) I tried

var imgObj = new Image();
        imgObj.src = b64;
        PageMethods.SaveImage(imgObj, success, error);

ain't working.

Help please. :(

Edit : Forgot to put the page html

 <div class="formRow">
        <input type="button" id="snap" value="Prendre photo" />
        <input type="button" id="send" value="Enregistrer Photo" />
    <br />
    <video id="video" width="320" height="240" autoplay></video>
    <canvas id="canvas" width="320" height="240"></canvas>

    </div>

I managed to get it done by making a new asp page and sending the b64 by parameter to that page.

New page :

public partial class SaveImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.Form["data"]))
        {
            string b64 = Request.Form["data"];
            byte[] binary = Convert.FromBase64String(b64);
             writeToFile(binary);
        }
    }

    public void writeToFile(byte[] array)
    {
        var fs = new BinaryWriter(new FileStream(Server.MapPath("~") + "/Images/Photo/" + Session["IdParticipantPhoto"].ToString() + ".png", FileMode.Append, FileAccess.Write));
        fs.Write(array);
        fs.Close();
    }
}

Jscript :

function sendPicture() {
    event.preventDefault();
    var b64 = document.getElementById("canvas")
    .toDataURL("image/png");
    b64 = b64.replace('data:image/png;base64,', '');
    console.log("Image   " + b64);
    $.ajax({
        type: 'POST',
        url: '/LAN/SaveImage.aspx',
        data: { "data": b64 },
        success: function (msg) {
            alert("Uploaded successfully");
        }
    });
}

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