How to get a photo taken from the Cam to keep it with MVC

0

I have a code that takes the picture activating the camera of the pc, encrypts it by passing it to base64:

    <video id="video"></video>
    <br>
    <button id="boton">Tomar foto</button>
    <p id="estado"></p>
    <canvas id="canvas" style="display: none;"></canvas>
    <script>

        function tieneSoporteUserMedia() {
            return !!(navigator.getUserMedia || (navigator.mozGetUserMedia || navigator.mediaDevices.getUserMedia) || navigator.webkitGetUserMedia || navigator.msGetUserMedia)
        }
        function _getUserMedia() {
            return (navigator.getUserMedia || (navigator.mozGetUserMedia || navigator.mediaDevices.getUserMedia) || navigator.webkitGetUserMedia || navigator.msGetUserMedia).apply(navigator, arguments);
        }

        // Declaramos elementos del DOM
        var $video = document.getElementById("video"),
            $canvas = document.getElementById("canvas"),
            $boton = document.getElementById("boton"),
            $estado = document.getElementById("estado");
        if (tieneSoporteUserMedia()) {
            _getUserMedia(
                { video: true },
                function (stream) {
                    console.log("Permiso concedido");
                    $video.src = window.URL.createObjectURL(stream);
                    $video.play();

                    //Escuchar el click
                    $boton.addEventListener("click", function () {

                        //Pausar reproducción
                        $video.pause();

                        //Obtener contexto del canvas y dibujar sobre él
                        var contexto = $canvas.getContext("2d");
                        $canvas.width = $video.videoWidth;
                        $canvas.height = $video.videoHeight;
                        contexto.drawImage($video, 0, 0, $canvas.width, $canvas.height);

                        var foto = $canvas.toDataURL(); //Esta es la foto, en base 64
                        $estado.innerHTML = "Enviando foto. Por favor, espera...";
                        var xhr = new XMLHttpRequest();
                        xhr.open("POST", "GuardarFoto", true);
                        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        xhr.send("archivo=" + encodeURIComponent(foto)); //Codificar y enviar

                        xhr.onreadystatechange = function () {
                            if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                                console.log("La foto fue enviada correctamente");
                                console.log(xhr);
                                $estado.innerHTML = "Foto guardada con éxito. Puedes verla <a target='_blank' href='./" + xhr.responseText + "'> aquí</a>";
                            }
                        }

                        //Reanudar reproducción
                        $video.play();
                    });
                }, function (error) {
                    console.log("Permiso denegado o error: ", error);
                    $estado.innerHTML = "No se puede acceder a la cámara, o no diste permiso.";
                });
        } else {
            alert("Lo siento. Tu navegador no soporta esta característica");
            $estado.innerHTML = "Parece que tu navegador no soporta esta característica. Intenta actualizarlo.";
        }
    </script>

In the controller I want to receive it using Request.File, and not by parameter in which I have to disengage from base64. The way I try to do it is like this:

[HttpPost]
        public ActionResult GuardarFoto()
        {


            //string temp = Server.UrlDecode(Request.Form["archivo"]).Replace("data:image/png;base64,", "");
            //byte[] arr = System.Text.Encoding.UTF8.GetBytes(Base64Decode(temp));

            //String Foldername_0 = Server.MapPath("~/Fotos/");

            //System.IO.File.WriteAllBytes(Foldername_0 +"Fotocam.png", arr);

            for (int j = 0; j < Request.Files.Count; j++)
            {
                var fileuploader = Request.Files[j];
                if (fileuploader.ContentLength > 0)
                {
                    string Foldername;
                    string Extension = System.IO.Path.GetExtension(fileuploader.FileName);
                    string filename = Path.GetFileName(fileuploader.FileName.ToString());
                    if (Extension == ".png" || Extension == ".jpg" || Extension == ".jpeg" || Extension == ".JPG")
                    {

                        Foldername = Server.MapPath("~/Fotos/");
                        fileuploader.SaveAs(Foldername + filename.ToString());
                    }
                }
            }

            return Json(new { responseText = "Fotos/Fotocam.png" });
        }

But when going through the for cycle the controller does not enter because it does not capture the file. I would like to know how I can send the photo from the view to the controller. I tried to do it this way, but it did not work either:

 <script>

        function tieneSoporteUserMedia() {
            return !!(navigator.getUserMedia || (navigator.mozGetUserMedia || navigator.mediaDevices.getUserMedia) || navigator.webkitGetUserMedia || navigator.msGetUserMedia)
        }
        function _getUserMedia() {
            return (navigator.getUserMedia || (navigator.mozGetUserMedia || navigator.mediaDevices.getUserMedia) || navigator.webkitGetUserMedia || navigator.msGetUserMedia).apply(navigator, arguments);
        }

        // Declaramos elementos del DOM
        var $video = document.getElementById("video"),
            $canvas = document.getElementById("canvas"),
            $boton = document.getElementById("boton"),
            $estado = document.getElementById("estado");
        if (tieneSoporteUserMedia()) {
            _getUserMedia(
                { video: true },
                function (stream) {
                    console.log("Permiso concedido");
                    $video.src = window.URL.createObjectURL(stream);
                    $video.play();

                    //Escuchar el click
                    $boton.addEventListener("click", function () {

                        //Pausar reproducción
                        $video.pause();

                        //Obtener contexto del canvas y dibujar sobre él
                        var contexto = $canvas.getContext("2d");
                        $canvas.width = $video.videoWidth;
                        $canvas.height = $video.videoHeight;
                        contexto.drawImage($video, 0, 0, $canvas.width, $canvas.height);
                        var cam = $canvas;
                        $estado.innerHTML = "Enviando foto. Por favor, espera...";
                        debugger;
                        //if ($canvas.length > 0) {
                                var data = new FormData();
                                for (var x = 0; x < cam.length; x++) {
                                    debugger;
                                    data.append("file" + x, $canvas.files[x]);
                                }

                                $.ajax({
                                    type: "POST",
                                    url: '/Cam/GuardarFoto',
                                    contentType: false,
                                    processData: false,
                                    data: data,
                                    success: function (result) {
                                        console.log(result);
                                    },
                                    error: function (xhr, status, p3, p4) {
                                        var err = "Error " + " " + status + " " + p3 + " " + p4;
                                        if (xhr.responseText && xhr.responseText[0] == "{")
                                            err = JSON.parse(xhr.responseText).Message;
                                        console.log(err);
                                    }
                                });

                        //}
                        //var xhr = new XMLHttpRequest();
                        //xhr.open("POST", "GuardarFoto", true);
                        //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        //xhr.send("archivo=" + encodeURIComponent(foto)); //Codificar y enviar

                        //xhr.onreadystatechange = function () {
                        //    if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                        //        console.log("La foto fue enviada correctamente");
                        //        console.log(xhr);
                        //        $estado.innerHTML = "Foto guardada con éxito. Puedes verla <a target='_blank' href='./" + xhr.responseText + "'> aquí</a>";
                        //    }
                        //}

                        //Reanudar reproducción
                        $video.play();
                    });
                }, function (error) {
                    console.log("Permiso denegado o error: ", error);
                    $estado.innerHTML = "No se puede acceder a la cámara, o no diste permiso.";
                });
        } else {
            alert("Lo siento. Tu navegador no soporta esta característica");
            $estado.innerHTML = "Parece que tu navegador no soporta esta característica. Intenta actualizarlo.";
        }
    </script>

If someone has any ideas, from now on, I would appreciate your help.

    
asked by Danilo 05.09.2018 в 20:08
source

2 answers

0

Base64 is not a file, but a string, so the Request.Files property will never have data.

You will have to get the base64 string of Request which is where you are sending it with the name of archivo :

string base64File = Request["archivo"];
byte[] bytesFoto = Convert.FromBase64String(base64File);
// procedes a guardar los bytes del archivo
    
answered by 06.09.2018 в 15:22
0

I found the solution, I'll publish it if someone has served him. First I must do a conversion before:

                    var blobBin = atob(foto.split(',')[1]);
                    var array = [];
                    for (var i = 0; i < blobBin.length; i++) {
                        array.push(blobBin.charCodeAt(i));
                    }
                    var file = new Blob([new Uint8Array(array)], { type: 'image/png' });
                    var formdata = new FormData();
                    formdata.append("file", file);

This is how it is:

 function tieneSoporteUserMedia() {
            return !!(navigator.getUserMedia || (navigator.mozGetUserMedia || navigator.mediaDevices.getUserMedia) || navigator.webkitGetUserMedia || navigator.msGetUserMedia)
        }
        function _getUserMedia() {
            return (navigator.getUserMedia || (navigator.mozGetUserMedia || navigator.mediaDevices.getUserMedia) || navigator.webkitGetUserMedia || navigator.msGetUserMedia).apply(navigator, arguments);
        }

        // Declaramos elementos del DOM
        var $video = document.getElementById("video"),
            $canvas = document.getElementById("canvas"),
            $boton = document.getElementById("boton"),
            $estado = document.getElementById("estado");
        if (tieneSoporteUserMedia()) {
            _getUserMedia(
                { video: true },
                function (stream) {
                    console.log("Permiso concedido");
                    $video.src = window.URL.createObjectURL(stream);
                    $video.play();

                    //Escuchar el click
                    $boton.addEventListener("click", function () {

                        //Pausar reproducción
                        $video.pause();

                        //Obtener contexto del canvas y dibujar sobre él
                        var contexto = $canvas.getContext("2d");
                        $canvas.width = $video.videoWidth;
                        $canvas.height = $video.videoHeight;
                        contexto.drawImage($video, 0, 0, $canvas.width, $canvas.height);

                        var foto = $canvas.toDataURL(); //Esta es la foto, en base 64
                        //$estado.innerHTML = "Enviando foto. Por favor, espera...";
                        //var xhr = new XMLHttpRequest();
                        //xhr.open("POST", "GuardarFoto", true);
                        //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        //xhr.send("archivo=" + encodeURIComponent(foto)); //Codificar y enviar
                        debugger;
                        var blobBin = atob(foto.split(',')[1]);
                        var array = [];
                        for (var i = 0; i < blobBin.length; i++) {
                            array.push(blobBin.charCodeAt(i));
                        }
                        var file = new Blob([new Uint8Array(array)], { type: 'image/png' });
                        var formdata = new FormData();
                        formdata.append("file", file);


                        $.ajax({
                            type: "POST",
                            url: '/Cam/GuardarFoto',
                            contentType: false,
                            processData: false,
                            data: formdata,
                            success: function (result) {
                                console.log(result);
                            },
                            error: function (xhr, status, p3, p4) {
                                var err = "Error " + " " + status + " " + p3 + " " + p4;
                                if (xhr.responseText && xhr.responseText[0] == "{")
                                    err = JSON.parse(xhr.responseText).Message;
                                console.log(err);
                            }
                        });
                        //xhr.onreadystatechange = function () {
                        //    if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                        //        console.log("La foto fue enviada correctamente");
                        //        console.log(xhr);
                        //        $estado.innerHTML = "Foto guardada con éxito. Puedes verla <a target='_blank' href='./" + xhr.responseText + "'> aquí</a>";
                        //    }
                        //}

                        //Reanudar reproducción
                        $video.play();
                    });
                }, function (error) {
                    console.log("Permiso denegado o error: ", error);
                    $estado.innerHTML = "No se puede acceder a la cámara, o no diste permiso.";
                });
        } else {
            alert("Lo siento. Tu navegador no soporta esta característica");
            $estado.innerHTML = "Parece que tu navegador no soporta esta característica. Intenta actualizarlo.";
        }
    
answered by 06.09.2018 в 17:28