I am using sql.js as an admin interface for a SQLITE3 database.
Basically sql.js provides an export method that returns a Uint8Array for the developer to further handle.
Goal: Have the user press a button and a "Save As" dialogue pops up to save a file that is a valid sqlite3 database.
What I've tried: This save code block I've found in various parts of the web researching this issue.
/* Uint8Array */
var binArray = db.export();
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
/* Is JSON.stringify necessary? */
var json = JSON.stringify(data),
/* Is type: "octet/stream" correct? */
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
saveData(binArray, "sqldb.sql");
It properly saves a file called "sqldb.sql", but I get "Invalid file format" error from a database client software.
application/octet-stream when you have binary data and no other MIME is more befittingJSON.stringify makes no sense, you end up with a String that looks like '{"0":254, "1":128, ...}' when you already have the binary data as you want to save itCombining these two points, the function returned should look more like this
// ...
return function (data, fileName) {
var blob = new Blob([data], {type: "application/octet-stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
You may also need to consider if the Uint8Array is really a complete .sql file in it's own right, i.e. if you did the call to get it not in a browser/ajax, but so it was written directly to disc (e.g. with curl or direct linked) would that file be a valid sql file?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With