Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to backup html 5 local storage data

am developing an offline application using html 5 and java script libraries. my system is for offline data collection. data is stored in the local machine in text format before being synced to the server later on. before i had developed the same application but using silver light which was easy to back up data for security reasons using

any idea on how i can backup the text files and zip them to my hard disk will be highly appreciated.

i have not found a solid answer through my research so far thanks in advance.

like image 713
JoseLuke Avatar asked Jul 12 '13 06:07

JoseLuke


2 Answers

One "solution" I can think of is, before the user closes the app using the close button, you could detect the window.onbeforeunload event and send the data to your server to save. But this is not reliable because there might be cases when the browser may crash or the user might forcefully close the browser application. Or worst of all if you are constantly using localStorage and by chance the user clears the browsing data (which includes localStorage) it will be gone.

But assuming you have the data at hand, you can send it to the server using POST and make a script to save it in the disk. Obviously, you might want to impose limitation on file size and enforce other security restrictions.

WARNING: PHP

Lets say you have a folder created for each unique user and all files in each user's folder are guaranteed to be named uniquely. In PHP you can use functions like file_put_contents() to save a text file, you can also easily ZIP it using the ZipArchive class.

It's not recommended to store this kind of data directly to the drive. I would highly recommend you to put the localStorage data in some kind of database and do a database backup instead of backing up individual user's data.

As other users have pointed it out you could also look at the HTML5 File API. Examples here.

like image 133
hyde Avatar answered Oct 04 '22 10:10

hyde


I found a solution on how to backup local storage files and zip them to my local drive without any server code. Below is a code snippet that works fine for me at least for now. Any modifications and enhancements will be highly appreciated.

if (localStorageKeys.length > 0) {
    for (var i = 0; i < localStorageKeys.length; i++) {
        var key = localStorageKeys[i];
        if (key.search(_instrumentId) != -1) {
            keysToBackup.push(key);
            var data = localStorage.getItem(localStorageKeys[i]);
            zip.file(localStorageKeys[i].slice(0, -19) + ".txt", data);
        }
        else {
            keysNotToBackup.push(key);
        }
        var datafile = document.getElementById('backupData');
        datafile.download = formName + "_Data.zip";
        datafile.href = window.URL.createObjectURL(zip.generate({ type: "blob" }));

    }
}
like image 22
JoseLuke Avatar answered Oct 04 '22 09:10

JoseLuke