Upload Image in Blob Format

Asked

Viewed 440 times

1

Good morning!

I am trying to send binary Blob data by Ajax to upload via PHP.

index.html:

document.getElementById("btnSave").addEventListener("click", event => {
            canvas.toBlob(function(blob){
                var reader = new FileReader();
                var obBlob = "";
                reader.readAsBinaryString(blob);
                reader.onload = function () {
                    console.log(reader.result)//retorna o binário
                    $.ajax({
                        url : "upload.php",
                        type: "POST",
                        data: {obBlob: reader.result},
                        contentType: false,
                        processData: false,
                        dataType:"text/plain",
                        success: function(resultado) {
                          console.log(resultado);
                        },
                        error: function(resultado) {
                            console.log(resultado);
                        }

                    });
                }//fim do reader
            });
        });

upload.php

$obBlob = !empty($_REQUEST["obBlob"])? $_REQUEST["obBlob"]: die("Nenhuma imgagem encontrada");
$servername = "localhost";
$username = "root";
$password = "";
$database = "fotos";
$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO fotos (foto) VALUES ($obBlob)";
if(mysqli_query($conn, $sql)){
    mysqli_close($conn);
    echo $conn->error;
}else{
    mysqli_close($conn);
    die("Error:".$conn->error);
}

The console log:

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} abort : ƒ (e) always : ƒ () catch : ƒ (e) done : ƒ () fail : ƒ () getAllResponseHeaders : ƒ () getResponseHeader : ƒ (e) overrideMimeType : ƒ (e) pipe : ƒ () progress : ƒ () promise : ƒ (e) readyState : 4 responseText : "Nenhuma imgagem encontrada" setRequestHeader : ƒ (e,t) state : ƒ () status : 200 statusCode : ƒ (e) statusText : "OK" then : ƒ (t,r,i)
__proto__ : Object

detail of the return of upload.php:

responseText : "No imgagem found"

I tried to pass the blob, nothing comes.... I even put dataType in Ajax because otherwise it can’t even find the index in $_REQUEST. However $_REQUEST is arriving empty! I tried to pass the binary, it also arrives empty... At least that’s what it seems to me!

I know there are several resolutions ready, but as I am learning, I would like to understand the reasons... I thank you for your help!

is giving error, and the console is returning the binaries and the following error:

responseText : "
Notice: Undefined index: obBlob in C: xampp htdocs WEBCAM upload.php online 2

I tried to pass Xmlhttprequest() also as follows:

document.getElementById("btnSave").addEventListener("click", event => {
   canvas.toBlob(function(blob){
      var oReq = new XMLHttpRequest();
      oReq.open("POST","upload.php", true);
      oReq.send(blob);
   });
});

Guys... I still can’t send... I tried this other way:

document.getElementById("btnSave").addEventListener("click", event => {
                canvas.toBlob(function(blob){
                                var json = JSON.stringify(blob);
                                console.log(json);
                                var xhr = new XMLHttpRequest();
                                xhr.open("POST", 'upload.php', true);
                                xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
                                xhr.send(json);
                });
            });

in this case, the json variable shows an empty object!

anyway, my best option was ajax, because the error in this case is coming from upload.php that is returning OK, but with the message "image not found".

But as I said at the beginning of this post, I am newbe in javascript... I do not know how to receive the error in this last case, so I am unanswered on the console... if anyone can give me some tips I am very grateful!

Valeuu!!

  • What mistake you accuse?

  • does not accuse! just nothing happens! even I put a true Return in upload.php at the beginning of the code to see if it would run $.post’s successful Alert but nothing happened tbm!

  • Document.getElementById("btnSave"). addeventlistener("click", Event => { canvas.toBlob(Function(blob){ $.post('upload.php',{blob}, Function(){ Alert("Photo successfully saved!" ); }); }); }). fail(Function(){ Alert( "error" ); });

  • put asism o js to see if error Alert appears and also checks the console (F12 in most browsers)

  • Uncaught Typeerror: Illegal Invocation at e (jquery-1.11.0.min.js:4) at Wc (jquery-1.11.0.min.js:4) at Wc (jquery-1.11.0.min.js:4) at Function.n.param (jquery-1.11.0.min.js:4) at Function.ajax (jquery-1.11.0.min.js:4) at Function.n.(/webcam/Anonymous Function) [as post] (http://code.jquery.com/jquery-1.11.0.min.js:4:22698) at (index):62 axo I am not including the right Jquery!

1 answer

1

Try to do it this way:

document.getElementById("btnSave").addEventListener("click", event => {
    canvas.toBlob(function(blob){        
        $.ajax({
            url : "upload.php",
            type: "POST",
            data: blob,
            contentType: false,
            processData: false,
            success: function() {
              alert("funcionou!");
            },    
            error: function() {
              alert("não funcionou!");
            }
        });
    });
});
  • with ajax he entered in success... just not saved in the comic, but must be some configuration here... Thanks anyway... because I wonder if with Jquery it didn’t work?

  • Missing contenttype and process $.post, at least that’s what I understood

  • Good morning... I’m having trouble passing the binary data... when I try to get the $_POST, nothing arrives.... open another topic or edit this? I changed the code a little bit!

  • just edit this one right here

  • I changed my code to transform the blob object in binary, but I still could not upload.php =//

Browser other questions tagged

You are not signed in. Login or sign up in order to post.