Node server (web-socket) crash - javascript

I'm trying to make a node.js server.
The following error can appear when a user disconect himself or when he refresh his page :
This is the code of my server :
var http = require("http");
var ws = require("C:/Program Files/nodejs/node_modules/npm/node_modules/nodejs-websocket/");
var colors = require('C:/Program Files/nodejs/node_modules/npm/node_modules/colors');
var fs = require("fs");
var request = "C:/Program Files/nodejs/node_modules/npm/node_modules/request";
http.createServer(function (req, res) {
fs.createReadStream("index.php").pipe(res)
}).listen(8080)
// ###################################################################################################################################
// ######################################################## CLASSE UTILISATEUR #######################################################
// ###################################################################################################################################
var utilisateur = function(){
}
// ###################################################################################################################################
// ########################################################## CLASSE SERVER ##########################################################
// ###################################################################################################################################
var tableauUtilisateur = new Array();
var server = ws.createServer(function (connection){
connection.trigramme = null
connection.on("text", function (str){
if (connection.trigramme === null){
newUtilisateur = new utilisateur();
connection.utilisateur = newUtilisateur;
connection.trigramme = str;
tableauUtilisateur.push(newUtilisateur);
}
else{
var code = str.substring(4,6);
var reste = str.substring(6,str.length);
switch(code){
case "01": // L'UTILISATEUR DEMANDE A SE CONNECTER
var postData={data:reste};
require(request).post({
uri:"http://localhost/php/seConnecter.php",
headers:{'content-type': 'application/x-www-form-urlencoded'},
body:require('querystring').stringify(postData)
},function(err,res,body){
if(body != "non"){
var infos = body.split("-1-2-3-4-5-6-7-8-9-");
connection.utilisateur.id = infos[1];
connection.utilisateur.trigramme = infos[2];
connection.utilisateur.nom = infos[3];
connection.utilisateur.prenom = infos[4];
connection.utilisateur.admin = infos[6];
connection.trigramme = infos[2];
console.log(("> "+infos[2]+" S\'EST CONNECTE AU SERVEUR AVEC SES IDENTIFIANTS.").grey);
connection.sendText("type01"+infos[0]+",,,,,"+infos[2]+",,,,,"+infos[3]+",,,,,"+infos[4]+",,,,,"+infos[5]+",,,,,"+infos[6]);
broadcastExcept("type07"+infos[2]+"("+infos[3]+" "+infos[4]+")",connection.utilisateur.id);
}
else
connection.sendText("type01non");
});
break;
case "02": // L'UTILISATEUR DEMANDE A CHANGER D'ANIMATION
reste += ",,,,,"+connection.utilisateur.id;
var postData={data:reste};
require(request).post({
uri:"http://localhost/php/modifierAnimation.php",
headers:{'content-type': 'application/x-www-form-urlencoded'},
body:require('querystring').stringify(postData)
},function(err,res,body){});
break;
case "03": // L'UTILISATEUR DEMANDE A SUPPRIMER UN COMPTE
if(connection.utilisateur.admin == 1){
var postData={data:reste};
require(request).post({
uri:"http://localhost/php/supprimerCompte.php",
headers:{'content-type': 'application/x-www-form-urlencoded'},
body:require('querystring').stringify(postData)
},function(err,res,body){
connection.sendText("type03"+body);
if(body == "oui")
console.log(("> "+connection.trigramme+" A SUPPRIME UN COMPTE DONT L'ID EST : "+reste).grey);
});
}
else
connection.sendText("type03non");
break;
case "04": // L'UTILISATEUR DEMANDE A CREER UN COMPTE
if(connection.utilisateur.admin == 1){
var postData={data:reste};
require(request).post({
uri:"http://localhost/php/creerCompte.php",
headers:{'content-type': 'application/x-www-form-urlencoded'},
body:require('querystring').stringify(postData)
},function(err,res,body){
connection.sendText("type04"+body);
if(body == "oui"){
console.log(("> "+connection.trigramme+" A CREE UN COMPTE DONT LE TRIGRAMME EST : "+reste.split(",,,,,")[0]).grey);
connection.sendText("type04"+body);
}
});
}
else
connection.sendText("type04non");
break;
case "05": // L'UTILISATEUR DEMANDE A CHANGER LE TYPE D'UN COMPTE
if(connection.utilisateur.admin == 1){
var postData={data:reste};
require(request).post({
uri:"http://localhost/php/changerTypeCompte.php",
headers:{'content-type': 'application/x-www-form-urlencoded'},
body:require('querystring').stringify(postData)
},function(err,res,body){
connection.sendText("type05"+body);
var valeur = reste.split(",,,,,")[1];
for(var cpt=0;cpt<tableauUtilisateur.length;cpt++){
if(tableauUtilisateur.id == reste.split(",,,,,")[0]){
tableauUtilisateur.admin = valeur;
}
if(valeur == 1)
console.log(("> "+connection.trigramme+" A DONNE LES DROITS ADMINISTRTEURS A "+reste.split(",,,,,")[2]).grey);
else
console.log(("> "+connection.trigramme+" A RETIRE LES DROITS ADMINISTRTEURS A "+reste.split(",,,,,")[2]).grey);
}
});
}
else
connection.sendText("type03non");
break;
case "06": // L'UTILISATEUR DEMANDE A SE CONNECTER AVEC SES COOKIES
var postData={data:reste};
require(request).post({
uri:"http://localhost/php/seConnecterCookies.php",
headers:{'content-type': 'application/x-www-form-urlencoded'},
body:require('querystring').stringify(postData)
},function(err,res,body){
if(body != "non"){
var infos = body.split("-1-2-3-4-5-6-7-8-9-");
connection.utilisateur.id = infos[1];
connection.utilisateur.trigramme = infos[2];
connection.utilisateur.nom = infos[3];
connection.utilisateur.prenom = infos[4];
connection.utilisateur.admin = infos[6];
connection.trigramme = infos[2];
console.log(("> "+infos[2]+" S\'EST CONNECTE AU SERVEUR AVEC SON ").grey+("COOKIE.").yellow);
connection.sendText("type01"+infos[0]+",,,,,"+infos[2]+",,,,,"+infos[3]+",,,,,"+infos[4]+",,,,,"+infos[5]+",,,,,"+infos[6]);
broadcastExcept("type07"+infos[2]+"("+infos[3]+" "+infos[4]+")",connection.utilisateur.id);
}
else
connection.sendText("type01non");
});
break;
case "08": // L'UTILISATEUR DEMANDE A MODIFIER SON MOT DE PASSE
reste += ",,,,,"+connection.utilisateur.id;
var postData={data:reste};
require(request).post({
uri:"http://localhost/php/modifierMotDePasse.php",
headers:{'content-type': 'application/x-www-form-urlencoded'},
body:require('querystring').stringify(postData)
},function(err,res,body){
if(body != "non"){
connection.sendText("type08"+body);
}
else
connection.sendText("type08non");
});
break;
}
}
})
connection.on("close", function (){
for(var cpt=0;cpt<tableauUtilisateur.length;cpt++){
if(tableauUtilisateur[cpt].trigramme == connection.trigramme){
console.log(("> "+connection.trigramme+" A QUITTE LE SERVEUR.").grey);
tableauUtilisateur.splice(cpt, 1);
}
}
})
})
server.listen(8081)
function broadcast(str){
server.connections.forEach(function (connection){
connection.sendText(str)
})
}
function broadcastExcept(str,except){
server.connections.forEach(function (connection){
if(connection.utilisateur.id != except)
connection.sendText(str)
})
}
The switch is here to distinct the type of the message (to connect, to talk, etc ...)
I looked at this link, but i don't understand or maybe it's not the same error :/
PS : i don't think the eror is in connection.on("close", function (){ because i tried to remove it and it was the same.

Related

Generate a CSV file from a JSON object

It's all in the title, I would like to generate a CSV file from the JSON objet get from this Ajax request,
The JSON I get represent all the recordings from a form :
I already have something that work for one field value a a single recording (the 0 here) :
<!DOCTYPE html>
<meta charset="utf-8"/>
<html>
<head>
<title>This is Website Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" type="text/javascript"></script>
<script src="../FileSaver.js"></script>
<script>
var formId = 566091
// Définition des paramètres de la requête HTTP
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.kizeoforms.com/rest/v3/forms/"+formId+"/data/readnew",
"method": "GET",
"headers": {
"content-type": "application/json",
"Authorization": "******",
}
}
// Envoi de la requête et affichage en console de la réponse
$.ajax(settings).done(function (response) {
console.log(response);
var ssa3 = [];
for (var i = 0 ; i <= response.data.length; i++) {
ssa3.push(response.data[i].fields.ssa_3_a_22h00.value);
}
//var ssa3 = response.data[0].fields.ssa_3_a_22h00.value;
var blob = new Blob([ssa3], {type: "application/csv;charset=utf-8"});
saveAs(blob, "ssa3.csv");
});
</script>
</head>
</html>
I would now like to have this field value for all the recordings, I have tried to push it into a table but console tells me "i is undefined"
$.ajax(settings).done(function (response) {
console.log(response);
var ssa3 = [];
for (var i = 0 ; i <= response.data.length; i++) {
ssa3.push(response.data[i].fields.ssa_3_a_22h00.value);
}
var blob = new Blob([ssa3], {type: "application/csv;charset=utf-8"});
saveAs(blob, "ssa3.csv");
});
Finally found it, I used a forEach to browse the data :
$.ajax(settings).done(function (response) {
console.log(response);
var ronde1n = [];
//on définit data qu'on va devoir parcourir avec un forEach
const data = response.data;
//on envoie les headers du fichiers csv
ronde1n.push("Numéro d'enregistrement,ID,Date et heure,conso SSA3");
//on parcours l'ensemble des enregistrements du formulaire Ronde 1 nuit
data.forEach(function (i) {
//on envoie les valeurs des champs qui nous intéressent pour chaque enregistrement
ronde1n.push("\r\n" + i.record_number + "," + i.id + "," + i.fields.date_et_heure.value + "," + i.fields.ssa_3_a_22h00.value);
});
//création du fichier CSV
var blob = new Blob([ronde1n], {type: "application/csv;charset=utf-8"});
saveAs(blob, "ronde1_nuit.csv");
});

One or more reserved bits are on: reserved1 = 0, reserved2 = 1, reserved3 = 1

In Chrome 50.0.2661.94 m
var a = new WebSocket('ws://192.168.0.153:9000/socket_listener_1_WINDOWS.php');
ERROR (from Yesterday afternoon- It works on the other clients pc's, but also "ws://echo.websocket.org/" works using my pc as client)
WebSocket connection to 'ws://192.168.0.153:9000/socket_listener_1_WINDOWS.php' failed: One or more reserved bits are on: reserved1 = 0, reserved2 = 1, reserved3 = 1
(what and where are "reserved1, 2 and 3"???)
This is the PHP script of the server (launched with XAMPP 3.2.2):
<?php
//error_reporting(E_ALL);
set_time_limit(0);
$IP = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : gethostbyname(gethostname());
echo $IP . '\r\n';
$host = $IP; //$_SERVER['SERVER_ADDR']; //host
$port = 9000; //port
$null = NULL;
$read = NULL;
$except = NULL;
function send_message($msg) {
global $clients;
foreach ($clients as $changed_socket) {
#socket_write($changed_socket, $msg, strlen($msg));
}
return true;
}
//Unmask incoming framed message
function unmask($text) {
$length = ord($text[1]) & 127;
if ($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
} elseif ($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
} else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i % 4];
}
return $text;
}
//Encode message for transfer to client.
function mask($text) {
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if ($length <= 125)
$header = pack('CC', $b1, $length);
elseif ($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif ($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header . $text;
}
//handshake new client.
function perform_handshaking($receved_header, $client_conn, $host, $port) {
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach ($lines as $line) {
$line = chop($line);
if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
$headers[$matches[1]] = $matches[2];
}
}
//var_dump($headers);
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//hand shaking header
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host\r\n" .
"WebSocket-Location: ws://$host:$port/socket_listener_1.php\r\n" .
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn, $upgrade, strlen($upgrade));
}
$ultimotimestamp = time();
//----------------------------------------------------------------------------------
//Così dovrebbe ripartire il socket in caso di crash
//Crea collegamento TCP/IP
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//Se non ci si può connettere all'indirizzo del socket, quindi il server è chiuso
//riparte tutto se il server non si connette
/* -E- */ while (#socket_connect($socket, $host, $port) === FALSE) {
//Parte un nuovo server
echo "SOCKET SERVER STARTED\n\n";
//Porta riutilizabile (DEFAULT SI)
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
//Crea collegamento TCP/IP
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//Lega il socket ad un indirizzo specifico
if (socket_bind($socket, $host, $port) !== FALSE) {
//mette il socket server in ascolto
socket_listen($socket);
//crea, e aggiunge il socket server alla lista
$clients = array($socket);
//comincia un loop che non si ferma mai
while (true) {
//la variabile changed prende la lista dei clienti (nel primo caso solo il server)
$changed = $clients;
//La funzione socket_select() accetta un array di socket e si mette in attesa di una variazione di stato su questi.
//Questa, derivando come background dai socket BSD, riconoscerà che questi array di risorse socket sono in realtà
//dei set di descrittori di file. Saranno monitorati 3 set di socket.
socket_select($changed, $read, $except, 10, 0);
//se in socket ci sono nuovi clients
if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); //accetta il nuovo socket (di default)
$header = socket_read($socket_new, 2048); //legge l'header del nuovo client, al quale inviare i dati
array_push($clients, $socket_new); //aggiunge alla lista dei clients il nuovo collegamento
if (!empty($header)) { //Se l'header non è vuoto
perform_handshaking($header, $socket_new, $host, $port); //fa un nuovo handshake, ossia una sorta di codifica dei dati
socket_getpeername($socket_new, $ip); //prende l'ip dal socket connesso
$response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' connected'))); //prepare json data
send_message($response); //notify all users about new connection
echo $ip . " connesso\n\n";
}
$found_socket = array_search($socket, $changed); //cerca array socket dentro changed
unset($changed[$found_socket]); //elimina l'indice trovato dall'array
}
if (time() - $ultimotimestamp >= 5) {
$response = mask(json_encode(array('type' => 'bip', 'message' => "1")));
send_message($response); //notify all users about new connection
$ultimotimestamp = time();
}
//ciclo dei socket connessi
foreach ($changed as $changed_socket) {
//scrive i dati del socket in un buffer di 2048 bytes
/* -E- */ //while (socket_recv($changed_socket, $buf, 2048, 0) > 0) {
while ($bytes = socket_recv($changed_socket, $buf, 2048, 0) > 1) {
//while (!false === ($buf = socket_read($changed_socket, 2048, PHP_BINARY_READ))) {
//var_dump($bytes);
//echo '\n\n';
$received_text = unmask($buf); //smaschera dati buffer
$tst_msg = json_decode($received_text); //decodifica in json
$response_text = mask(json_encode($tst_msg)); //lo rimaschera
send_message($response_text); //invia il dato a $changed_socket, che è una risorsa socket
echo $response_text . "\n\n"; //Mostra il dato inviato a schermo
break 2; //esce fino al ciclo while (di 2 livelli sopra)
}
//il buffer legge il socket di prima, fino a 2048 bytes
/* -E- */ //if (socket_recv($changed_socket, $buf, 2048, 0) === FALSE) { // se il $buf è false, quindi si presuppone che il client sia disconnesso
if ($bytes = socket_recv($changed_socket, $buf, 2048, 0) === FALSE) {
var_dump($bytes);
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]); // rimuove il client dall'array dei clients
}
}
//sleep(0.05);
}
socket_close($socket); //in caso di errore del ciclo si chiude il socket in ascolto
}
socket_close($socket);
}
socket_close($socket);
SERVER SCREEN:
CLIENT SCREEN
This is the Wireshark TCP trace from my client. Ask me if you need new screenshots.
I have no Firewalls and Antivirus activated. Do you know why it doesn't work on my pc? It worked for 1 year first.
Thank you
In my experience, even RFC6455 didn't remarks RSV1, but I have tested it is representing "isMasked" on Chrome.

function call in node js using socket

I'm trying to call a function which is created in another "class", and I want to use it in the socket.on (...) but it is not working , it keeps showing
this.function is not a function.
here is the code
//calling the function
Serveur.prototype.traitementSurConnection = function(socket) {
var that = this
socket.on('connection', function (creator, typeArtifact,idConteneur, typeConteneur) {
that.addArtifact('momo', 'img', 1,0);
})
};
//the function
ZoneCollaborative.prototype.addArtifact = function(creator, typeArtifact,idConteneur, typeConteneur) {
// calcul d'un nouvel identifiant
var id = this.setIdAr();
console.log(' *** ZC : calcul nouveau IdArtifact = '+id);
// création de l'artifact
var monArtifact = new Artifact(id, creator, typeArtifact, idConteneur,
typeConteneur);
console.log(' *** ZC : creation artifact'+monArtifact.getId() );
// ajout à la liste
this.artifacts.push(monArtifact);
console.log(' *** ZC : total artifact ='+ this.artifacts.length);
};
here is the ful code of bothe Serveur.js and ZoneCollaborative.js
//Serveur.js
var http = require('http');
var socket = require('socket.io');
var ZP = require('./ZonePartage');
var Constantes = require('./Constante');
//création des constantes
var CONSTANTE = new Constantes();
function Serveur(ZP, port) {
this.ZP = ZP;
this.port = port;
console.log(" ---- Creation d'un serveur pour la ZP (" + ZP.getId()
+ ") sur le port " + port);
var serveur = http.createServer(function(req, res) {
});
serveur.listen(this.port, function() {
console.log(' ---- Server en ecoute sur port ' + port);
});
//
var io = require('socket.io').listen(serveur);
console.log(' ---- Socket en ecoute sur port ' + port);
browser = require('iotdb-arp');// module qui s'occupe de la determination de l'adress MAC
io.sockets.on('connection', (function(socket) {
console.log(' ---- Socket connection');
console.log('un utilisateur est connecté');
browser.browser({}, function(error, d) {
if (error) {
console.log("#", error);
} else if (d) {
var adresse = d.ip;
console.log('son adresse ip est ' + adresse); //obtenir l'adress ip de l'utilisateur connecté
}
});
socket.on('disconnect', function() {
console.log(' ==> 1 utilisateur déconnecté <== '); //déconnection
});
this.traitementSurConnection(socket);
}).bind(this));
console.log(' ---- Socket en attente de traitement port ' + port);
}
module.exports = Serveur;
Serveur.prototype.demandConnexion = function(idZEP) {
if (this.ZP.createZE(idZEP))
{
console.log(' ==> socket : demande de creation ZE pour ' + idZEP
+ ' accepte');
}
else
{
console.log(' ==> socket : demande de creation ZE pour ' + idZEP
+ ' refuse');
}
};
Serveur.prototype.traitementSurConnection = function(socket) {
console.log(' ==> socket connexion');
var self = this;
socket.on('connection', function(creator, typeArtifact, idConteneur,
typeConteneur) {
self.addArtifact('momo', 'img', 1, 0);
})
}
});
//ZoneCollaborative.js
ZoneCollaborative.prototype.addArtifact = function(creator, typeArtifact,idConteneur, typeConteneur) {
// calcul d'un nouvel identifiant
var id = this.setIdAr();
console.log(' *** ZC : calcul nouveau IdArtifact = '+id);
// création de l'artifact
var monArtifact = new Artifact(id, creator, typeArtifact, idConteneur,
typeConteneur);
console.log(' *** ZC : creation artifact'+monArtifact.getId() );
// ajout à la liste
this.artifacts.push(monArtifact);
console.log(' *** ZC : total artifact ='+ this.artifacts.length);
};

Edit Table Localstorage and Javascript/Jquery

I need to edit the table stored in localStorage and json, how could it? I'm new and I could only save but not to edit these items in the table.
Javascript and Jquery
$( document ).ready(function() {
cargarDatos();
//document.getElementById('btnGuardar').onclick = mostrarDatos;
$('#frmContacto').submit(function(event) {
event.preventDefault(); //Bloqueo de comportamiento por defecto de formulario
guardarDatos();
cargarDatos();
});
$('input').on('blur', function(){
$(this).addClass('marcado');
});
$('.btnEditar').on('click', function(event){
event.preventDefault(); //Bloqueo de comportamiento por defecto de formulario
id = this.id;var link = this.href;
alert(link);
id = link.substr(link.indexOf("#"), link.length);
alert(id);
editarDatos();
});
$('#inputFoto').on('change', function(e) {
precargarImagen(this);
});
});
//Colección de contactos
//var contactos = new Array();
function guardarDatos(){
name = $('#inputNombre').val();
direccion = $('#inputDireccion').val();
telefono = $('#inputTelefono').val();
fecha = $('#inputFecha').val();
email = $('#inputEmail').val();
color = $('#inputColor').val();
dataFoto = $("#imgFoto").attr("src");
contacto = {
nombre : name,
direccion : direccion,
telefono : telefono,
fecha : fecha,
email : email,
color : color,
foto : dataFoto
};
contactos.push(contacto);
console.log(JSON.stringify(contactos));
localStorage.setItem('lstcontactos2', JSON.stringify(contactos));
}
function cargarDatos(){
var data = localStorage.getItem('lstcontactos2');
contactos = data && JSON.parse(data);
if(contactos==null)
contactos = new Array();
$('#tablaContactos').bootstrapTable({
data: contactos
});
}
/**
* Formato asociado a tabla boostrapTable para el campo de acciones, con la finalidad
* que asocie un boton para editar la tarea que posterior sera capturado en el evento clic
* #param value Id de la tarea
*/
function btnEditar(value){
console.log("valueformat " + value);
return '<span class="glyphicon glyphicon-pencil"></span>';
}
function imgFoto(value){
return '<img id="imgFoto" src="' + value +
'" style="width:auto;height:160px;">';
}
/**
* Recupera del input:file el archivo seleccionado y lo renderiza en la pantalla
* #param inputfile Objeto input de tipo file sobre el que se esta seleccionado la imagen
*/
function precargarImagen(inputfile){
var file = inputfile.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = reader.result;
$(".file-caption-name").html(file.name);
$(".file-preview-frame").empty();
$(".file-preview-frame").
append('<img id="imgFoto" src="' + reader.result +
'" style="width:auto;height:160px;">');
};
reader.readAsDataURL(file);
inputfile.val(img.src);
} else {
alert("Archivo no soportando!");
}
}
How i did? Examples? i'm new please.

Working with blob, XMLHttpRequest and WebSQL - Trying to save blob into WebSQL and then recover to window.URL.createObjectURL

it's my frist question here on stackoverflow. I tryed search here and at Google ways to:
Convert file into blob, save it in WebSQL, then select it from the database and shows with window.URL.createObjectURL
So... Almost everything is done I've already converted to blob with XMLHttpRequest saved into WebSQL (I've chosen WebSQL for mobile use purpose) but I don't figure out how to get the binary text re-converted to blob and open with window.URL.createObjectURL. I've already tried several ways to do that including using Blob builder, it writes the URL but with nothing (404 error)
Here follows my code, the comments are in portuguese, but any question, just ask.
I set the query to ID=1 and result[0] just to test.
<script>
window.URL = window.URL || window.webkitURL; //Instancia o window.URL
var xhr = new XMLHttpRequest(); //Instancia o XHMLHttpRequest
window.onload = function(){
var status = document.getElementById("status");
status.innerHTML = "Aplicação Carregada";
potti.webdb.open();//Abre o Banco
potti.webdb.createTable();//Cria a tabela
getBinary("http://www.belenosonline.com/Blob/1.pdf");//Pega o arquivo
}//Fim onload
function getBinary(url){
if(xhr != null){//Se ele conseguir criar o HMLHttpRequest
xhr.open("GET", url, true);//Abre a conexão GET para o arquivo de forma assincrona (true)
xhr.responseType = "text";
xhr.onreadystatechange = xhrHandler;//State Handler
xhr.send(null);//Não envia nada
}
else{
alert("Seu navegador não é suportado, por favor, atualize-o");
}
}
xhrHandler = function(){
if(xhr.readyState == 3){
status.innerHTML = "Carregando Arquivo";
}
else if(xhr.readyState == 4){
if(xhr.status == 200){
status.innerHTML = "Arquivo Carregado com Sucesso";
var conteudo = xhr.responseText;
potti.webdb.insert("Mozilla",conteudo);
}
else{
status.innerHTML = "Houve um erro no processamento do arquivo";
}
}
else{
status.innerHTML = "Houve um erro no processamento do arquivo";
}
}
//Encapsula o Banco de dados
var potti = {};
potti.webdb = {};
potti.webdb.db = null;
//Abre o BD
potti.webdb.open = function() {
var dbSize = 50 * 1024 * 1024; // 50MB
potti.webdb.db = openDatabase("TestBD", "1.0", "Teste", dbSize);
}
//Cria a tabela no banco
potti.webdb.createTable = function() {
var db = potti.webdb.db;
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS TestTable(ID INTEGER PRIMARY KEY ASC, nome TEXT ,conteudo TEXT)", []);
});
}
//Insere dados no Banco
potti.webdb.insert = function(nome,conteudo){
var db = potti.webdb.db;
db.transaction(function(tx){
status.innerHTML = "Gravando no Banco";
tx.executeSql("INSERT INTO TestTable(nome, conteudo) VALUES (?,?)",
[nome, conteudo],
potti.webdb.onSuccess,
potti.webdb.onError);
});
}
//Carrega dos dados
potti.webdb.loadData = function() {
var db = potti.webdb.db;
var result = [];
db.transaction(function (tx) {
tx.executeSql("Select * TestTable WHERE ID = 1", [], function(tx, rs){
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i);
result[i] = {
"Id" : row["ID"],
"Nome" : row["nome"],
"Conteudo" : row["conteudo"],
};
}
var blob = new Blob([result[0].Conteudo], { type: 'application/pdf' });
console.log(window.URL.createObjectURL(blob));
}, potti.webdb.onError);
});
}
//Erro no Banco de Dados
potti.webdb.onError = function(tx, e) {
console.log("Houve um erro " + e.message);
}
//Sucesso no Banco de Dados
potti.webdb.onSuccess = function(tx, r) {
document.getElementById("status").innerHTML = "Salvo no Banco";
potti.webdb.loadData();
}
</script>
after 2 weeks trying I got it with a issue here on stackoverflow: Retrieving binary file content using Javascript, base64 encode it and reverse-decode it using Python
You have to get a Arraybuffer > Convert to Base64 > Store > Get > Decode to ArrayBuffer > Create Blob

Categories