I am trying to send Blob binary data via Ajax to upload via PHP. However, I am not able to access $ _GET. Returns an error saying undefined index:
responseText: "No images found"
When I comment the upload.php die () line:
responseText: "↵Notice: Undefined index: obBlob in C: \ xampp \ htdocs \ WEBCAM \ upload.php on line 4
AJAX return 'error':
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, ...} abort: ƒ (e) always: ƒ () catch: ƒ (e) done: ƒ () fail: ƒ () getAllResponseHeaders: ƒ () arguments: (...) caller: (...) length: 0 name: "getAllResponseHeaders" prototype: {constructor: ƒ} proto : ƒ () [[FunctionLocation]]: jquery-3.3.1.min.js: 2 [[Scopes]]: Scopes [3] getResponseHeader: ƒ (e) overrideMimeType: ƒ (e) pipe: ƒ () progress: ƒ () promise: ƒ (e) readyState: 4 responseText: "No image found" setRequestHeader: ƒ (e, t) state: ƒ () status: 200 statusCode: ƒ (e) statusText: "OK" then: ƒ (t, r, i) proto : Object
follow the code:
index.html (full):
<!doctype html>
<html lang="pt">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<title>Webcam TRIX</title>
</head>
<body>
<video src="" id="video" muted autoplay></video>
<canvas id="pic"></canvas>
<!-- colocar um form com um action para salvar a foto -->
<input type="text" id="blobOut" value="">
<img alt="" src="" id="picOut"/>Foto
<input type="button" id="btnStart" value="Tirar Foto">
<input type="button" id="btnSave" value="Salvar Foto">
<script type="text/javascript">
//inicializa um objeto stream
var tmpStream;
function setMedia(video, s){
tmpStream=s;
try{
video.srcObject = s;
}catch(error){
video.src = URL.createObjectURL(s);
}
}
//função para iniciar a camera
function startCamera(){
navigator.mediaDevices.getUserMedia({
video:{facingMode:"environment"},
audio: true
})
.then((stream) => {
setMedia(document.getElementById("video"),stream);
});
}
//função para parar a camera
function stopCamera(){
if(!tmpStream) return;
tmpStream.getVideoTracks().forEach(track => track.stop());
}
//ligar a camer automaticamente
window.addEventListener("DOMContentLoaded", startAll);
//incicializa tudo
function startAll()
{
startCamera();
//função para tirar foto
document.querySelector("#btnStart").addEventListener("click", event => {
canvas = document.getElementById("pic");
const context = canvas.getContext("2d");
const video = document.getElementById("video");
//tamanho da foto mesmo tamanho do video
canvas.width = video.offsetWidth;
canvas.height = video.offsetHeight;
//desenha o video no canvas
context.drawImage(video, 0, 0, canvas.width, canvas.height);
});
}
document.getElementById("btnSave").addEventListener("click", event => {
canvas.toBlob(function(blob){
$.ajax({
url : "upload.php",
type: "POST",
data: {obBlob: blob},
contentType: false,
processData: false,
dataType:"json",
success: function(resultado) {
console.log(resultado);
},
error: function(resultado) {
console.log(resultado);
}
});
});
});
</script>
</body>
</html>
upload.php (full):
<?php
header("Content-Type: application/json", true);
if(empty($_GET["obBlob"])) die("Nenhuma imgagem encontrada");
$obBlob = $_GET["obBlob"];
$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);
}
?>
EDIT:
I tried the following way, using the FormData API with AJAX, to no avail:
document.getElementById("btnSave").addEventListener("click", event => {
canvas.toBlob(function(blob){
var formData = new FormData();
formData.append("obBlob", blob);
$.ajax({
url : "//localhost/webcam/upload.php",
type: "POST",
data: {obBlob: formData},
contentType: false,
processData: false,
success: function(resultado) {
console.log(resultado);
},
error: function(resultado) {
console.log(resultado);
}
});
});
});
document.getElementById("btnSave").addEventListener("click", event => {
canvas.toBlob(function(blob){
json = JSON.parse(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);
});
});
How do I get the error in this last case case? any idea what it might be?
EDIT 2:
I gave up using blob and tried with canvas.toDataURL, but the array arrives empty !!!
document.getElementById("btnSave").addEventListener("click", event => {
var dataURL = canvas.toDataURL();
$.ajax({
url : "//localhost/webcam/upload.php",
type: "POST",
data: {"imgBase64":dataURL},
contentType: false,
processData: false,
dataType:"json",
success: function(resultado) {
console.log(resultado);
},
error: function(resultado) {
console.log(resultado);
}
});
});
When I check the payload on the network tab of the Chrome developer tools, the object is there!
I have tried everything and it does not come out said ... I checked the $ _SERVER ['REQUEST_METHOD'] and it is returning POST, I tried to pass using XMLHttpRequest ... I have no idea what it might be ... I am at the base of the attempt and error!