3

I was about to ask 'How to "download" localStorage?' but fortunately found this and my original question was solved.

Now then, how can I allow the user to "upload" a local file to localStorage or javascript in general? I'm not asking the way to access the local files in background which is clearly prohibited; I want the user to select their local file explicitly.

For example, if the user has save.json:

{
    "hp": 32,
    "maxHp": 50,
    "mp": 11,
    "maxMp": 23
}

How can I set this to localStorage by just asking the user to upload this file?

akai
  • 2,294
  • 3
  • 20
  • 44
  • This was already answered here: https://stackoverflow.com/questions/16505333/get-the-data-of-uploaded-file-in-javascript – Aaron Franco Mar 03 '18 at 17:59

1 Answers1

8

Here is an example of a user uploading a save.json file. You can open this in a browser and upload your own save.json file. Refresh the page and inspect the console to see the saved json printed out. I've included a fiddle, but there an issue with using localStorage within JSFiddle.

<html>
    <input type="file" name="files[]" id="fileUpload">
    <script type="text/javascript">
            (function() {
                // Key for local storage, use to save and access.
                var FILE_KEY = 'save.json';

                // fire processUpload when the user uploads a file.
                document.querySelector('#fileUpload').addEventListener('change', handleFileUpload, false);

                // Log any previously saved file.
                console.log('previous save: ', retrieveSave());

                // Setup file reading
                var reader = new FileReader();
                reader.onload = handleFileRead;

                function handleFileUpload(event) {
                    var file = event.target.files[0];
                    reader.readAsText(file); // fires onload when done.
                }

                function handleFileRead(event) {
                    var save = JSON.parse(event.target.result);
                    console.log(save) // {hp: 32, maxHp: 50, mp: 11, maxMp: 23}
                    window.localStorage.setItem(FILE_KEY, JSON.stringify(save));
                }

                function retrieveSave() {
                    return JSON.parse(localStorage.getItem(FILE_KEY))
                }
            })();
    </script>
</html>
William Fleming
  • 456
  • 2
  • 7