I have to import the data saved in a .csv file and then save this to localstorage.
I previously worked on a script to export date to .csv and now I must do the reverse.
I know I will need to do the following:
- Get the file
- Parse the file into a blob
- Save it to local storage
I have tried the following:
-
Get the file
<input id="csv" type="file">
It works! -
Parse the file into a blob or object I think…
let csvData = [];
let csvData = fileInput.addEventListener('change', readFile);
Does not work! I get a csvData undefined error when Iconsole.log(csvData);. -
Save it to local storage
let csvData = [];
localStorage.setItem("csvData", JSON.stringify(CSV_DATA));
It works!
Can anyone see what I am doing wrong or mmissing? Perhaps it is the the wrong type of object. I am still learning so I am sorry if it is obvious.
I did search but none of the examples are for vanilla JS.
The code is very disjointed becasue I suck lol, seriously though, I am trying to rebuild the code from an example I found in another question on here. The code I tried to hack was designed to print the output to am HTML element and I need to go to localstorage
This is the entire code:
<body>
<p>Select local CSV File:</p>
<input id="csv" type="file">
<script>
var fileInput = document.getElementById("csv"),
readFile = function () {
var reader = new FileReader();
reader.onload = function () {
document.getElementById('out').innerHTML = reader.result;
};
// start reading the file. When it is done, calls the onload event defined above.
reader.readAsBinaryString(fileInput.files[0]);
};
let csvData = [];
let csvData = fileInput.addEventListener('change', readFile);
let CSV_DATA[];
localStorage.setItem("csvData", JSON.stringify(CSV_DATA));
</script>
</body>
>Solution :
Move the localStorage.setItem("csvData", JSON.stringify(CSV_DATA)); inside the readFile function.
const fileInput = document.getElementById('csv')
const readFile = () => {
const reader = new FileReader()
reader.onload = () => {
document.getElementById('out').innerHTML = reader.result;
localStorage.setItem("csvData", JSON.stringify(reader.result));
}
reader.readAsBinaryString(fileInput.files[0])
}
fileInput.addEventListener('change', readFile)