Save Javascript file object to local storage - javascript

I have a input type file where I save the file to a file object like so
var uploadControl = document.getElementById("fileUpload");
var files = uploadControl.files[0];
Then I would like to save that file to local storage to read into the FileReader object at a later time. Does anyone know if this is possible. I have tried several different options and every time I try and retrieve the object out of local storage, it is undefined.
Here are some things I have tried
var setObj = {"prop": "myProp", "file": files};
chrome.storage.sync.set({"myObj":setObj});
This doesn't throw errors, but when I try and retrieve the object, it is undefined
chrome.storage.sync.get("myObj", function(item) {
console.log("item name: " + item.myObj.file.name);
});
However I can access the other properties of the object
chrome.storage.sync.get("myObj", function(item) {
console.log("item prop: " + item.myObj.prop);
});
Am I doing something wrong when adding the object to local storage or am I accessing it incorrectly? Or is it just impossible to do this?

localStorage can only contain string name/value pairs, which means you can not store an object directly.You can use stringify and parse for that.

Related

Save/Load Variables in js

I'm trying to create a save/load function for my game in js, but I have basically no idea with how to go through with doing this. I can save variables to a JSON file or LocalStorage, but I don't know how to load them back into the program. I'm also pretty sure I'm exporting variables the wrong way as well. Any help?
Normally, I use JSON format to store and read data (of any type).
To save data (using key gamedata as example):
var myData = {
name: 'David',
score: 10
}
localStorage.setItem('gamedata', JSON.stringify(myData));
** without JSON.stringify, you data will be saved as string [Object object]
To retrieve the data back:
var savedData = localStorage.getItem('gamedata'); // savedData is string
var myData = JSON.parse(savedData); // parse JSON string to java object
setup a bin on www.myJSON.com. p5 has built in functionality for ajax requests such as loadJSON. that way it's not in local storage and you can access your data if you have it on github. I know your struggle, I used to deal with this sort of issue myself before I found myJSON

Store JSON to localstorage not working

After pushing a button I would like to save an item (nested JSON) into a new Array and store it to the localstorage.
addFavourite(card) {
console.log(JSON.stringify(card));
var cards = [];
this.cardfavouriteArray.push.apply(cards, card)
this.storage.set('favouriteData', this.cardfavouriteArray);
}
getData() {
var data = this.storage.get('favouriteData');
if(data){
this.storage.get('favouriteData').then((val) => {
console.log('test', JSON.stringify(val));
});
}
I get no error, but 'test' is always empty. I need it as an array.
Set and Get method for localstorage varies on which service you are using
1.HTML5 localStorage- If you are using HTML5 localStorage directly then you should use localStorage.getItem
and localStorage.setItem
2.localstorage is limited to store only string key/value pairs.Use JSON.stringify and JSON.parse when using setting and getting from localstorage
addFavourite(card) {
console.log(JSON.stringify(card));
var cards = [];
this.cardfavouriteArray.push.apply(cards, card)
this.storage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));
}
getData() {
var data = this.storage.get('favouriteData');
if(data){
this.storage.getItem('favouriteData').then((val) => {
console.log('test', JSON.parse(val));
});
}
3.ng2-webstorage- In case of ng2-webstorage this.storage.retrieve and this.storage.store will work.
Change this.storage.set('favouriteData', this.cardfavouriteArray); to localStorage.set('favouriteData', JSON.stringify(this.cardfavouriteArray)); (It's a pre-defined method by angular). Also stringify the array.
Set array in local storage like this:
localStorage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));
Get array from local storage like this:
var data = JSON.parse(localStorage.getItem('favouriteData'));
Explanation: It is because localstorage can not store object, it stores in string format. So we need to JSON.stringify the object. Also localStorage has function name setItem and getItem as defined here: http://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage. When we get the string from localstorage, we need to JSON.parse to convert it back to object.
You are using this.storage.set and this.storage.get. It is not clear which library are you using, but the code I mentioned will work in Angular or any framework. Since localStorage.setItem and localStorage.getItem is pure javascript.

load JSON with JQuery

Is it possible to load JSON file once, and in further call will use loaded JSON (for ex. from cache)?
The easiest way to achieve this is to use the localStorage of JavaScript.
Let's assume you have an object named object.
You can store it this way:
// parse Object to JSON, then store it.
let jsonObject = JSON.stringify(object);
localStorage.setItem('myObject', jsonObject);
And if you want to use it again, do it this way:
// load it from storage and parse the JSON to Object.
let jsonObject = localStorage.getItem('myObject');
let object = null;
if(jsonObject){
object = JSON.parse(jsonObject);
}
Then change it according to your needs and store it again.
You can delete it by
localStorage.removeItem('myObject');
There are so many ways,
You can store your JSON file in assets folder and read them like this - https://stackoverflow.com/a/19945484/713778
You can store it in res/raw folder and read the same as show here - https://stackoverflow.com/a/6349913/713778
For basic JSON parsing, Android's in-built JSONObject should work - https://developer.android.com/reference/org/json/JSONObject.html
For more advanced JSON parsing (json-java mapping), you can look at GSON library - https://code.google.com/p/google-gson/

What is the Possible Approach to read a .property file and populate the map in javascript

I have a property file local.properties
key1=value1
key2=value2
how can i read this property file in javascript and create a map of this key value pair .
<script type="text/javascript">
function(){
//reading of file
}
</script>
Thanks .
Thinking your property file follow this struture and the page doesn't access the file directly (because javascript can't access disk directly), you can do something like...
var propertFileStr = "key1=value1 key2=value2";
var strVet = propertFileStr.split(" ");
var obj = {};
strVet.forEach(function(item){
obj[item.split("=")[0]] = item.split("=")[1];
});
console.log(obj);
In this example, propertFileStr is completed with base in uploaded file and each property divided by a space, and then it's possible the catch each property and then convert it to key value object.

Chrome Extension: StorageArea.Set key being passed as string

Good evening,
I'm trying to save an associative array into chrome.storage.local, like so:
var keyName = 'name';
var data = //grabbed from an Ajax call
saveData(keyName, data);
function saveData(keyName, data){
console.log("saving with key: "+keyName);
chrome.storage.local.set({keyName:data});
}
To check to make sure the data saved properly, I load:
function loadData(keyName){
console.log("loading: "+keyName);
chrome.storage.local.get(keyName, function(result){
console.log(result);
});
}
The log shows it is trying to load the correct key name, but nothing comes up. I then try calling loadData(null), which will show the entire contents of the local storage, and I find:
Object {keyName: Array[3]}
keyName: Array[3]
__proto__: Object
My data! But the key it saved with is "keyName" instead of "name". The log from saveData outputs that it is "saving with key 'name'", but it's saving with key "keyName" instead...
????
Thanks!
How strange...
Seems my question is similar to Using a variable key in chrome.storage.local.set
The answer they found was to convert the JSON {keyName:data} to an object:
var obj = {};
obj[keyName] = data;
chrome.storage.local.set(obj);
This works.
Is this because the JSON field is automatically passing as a string?

Categories

Resources