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

StackOverflow https://stackoverflow.com/questions/15349821

Question

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>

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top