0

I am creating a small html5 app that will allow users to change color properties of some elements. I want to give the user the option to save their changes and then upload them on later occasion (without registration). For this, I added a button that produces a text file of their properties, I want to add a button that will allow them to upload the file, I created a file picker dialog,

<label>  
  <input class="button" 
         type="file" 
         name="input-name" 
         style="display:none;" 
         onchange="read(event)"/>
  <span id="input-file" >Select File</span>
</label>

But I can't figure how do I open this file in javascript and process its content. I know this should be similar to this

function read(evt){
    var file = document.getElementById("input-file");
    //checking for file reader
    if (window.File && window.FileReader && window.FileList && window.Blob){
        var r = new FileReader();
        r.readAsText(file);
    } else{
        alert("Browser not supported");
    }
}

But this doesn't work because file above is not the path to the file but the object. How do I get the path to the file? Is there a better way to do this?

2 Answers 2

1

You can read files via the File API, but you can't save them. You can create windows containing the text you want to save and then let the user save it, but it's a pain both when saving and loading.

Fortunately, for what you're talking about, you don't want files.

Instead, store the color preferences in web storage, specifically localStorage:

Loading (e.g., on page load or whenever):

var savedColor = localStorage.getItem("saved-color");
if (savedColor == null) {
    // There wasn't one, use a default
}

Saving:

localStorage.setItem("saved-color", savedColor);

(localStorage in the above isn't a placeholder or anything; it's a global that's present on browsers that support local storage, which is [just about all of them2.)

Web storage values are always strings. You can use JSON if you need to store complex things.

Sign up to request clarification or add additional context in comments.

11 Comments

Remember that localStorage is slow and limited in size. Also, it isn't available in old IE. You can use a library to handle all that.
@IsmaelMiguel: Local storage isn't slow, certainly not in comparison to files. It's supported by all modern browsers, and also IE8; I think in 2016 we can stop worrying about IE7 and earier. Storage limits are in the megabytes; this use case sounds likt it will be, at most, a couple of hundred bytes.
I agree with most of what you said. But still, you really can't say "we can stop worrying about IE7". Sadly, there's still people stuck with Windows XP or even older (Windows NT). So, you can't really say it. For most cases, yes. For something specific, no. We don't know anything about the expected environment where the code will run since that information wasn't provided.
@IsmaelMiguel: IE8 runs on Windows XP. Yes, we can disregard IE7 and earlier. IE7 has a market share of 0.64%; IE6 is down at 0.31%. Even IE8 only has ~7.5% market share -- which is those people stuck on XP you mentioned. :-) If there were a specific restriction to use IE7, the OP wouldn't be trying to use the File API in the first place. :-)
Why not? There's a polyfill/shim for that: github.com/Modernizr/Modernizr/wiki/…
|
1

Assuming your text file is in JSON (stringified format), i.e. your file.txt contains {"primary":"green","secondary":"#FF0000"}

<input type="file" id="file-picker" accept="text/plain" />

/*
 Assuming JSON format in the text file - e.g:

 var colors = {
     primary: 'green',
     secondary: '#FF0000'
  }
  JSON.stringify(colors);

  output: '{"primary":"green","secondary":"#FF0000"}'
*/

var fileInput = document.querySelector('#file-picker');

function readFileJSON(file) {
  return new Promise(function(resolve) {

    var reader = new FileReader();

    reader.onload = function(e) {
        try {
          resolve(JSON.parse(e.target.result));
        } catch(ex) {
          throw ex;
        }
    };

    reader.readAsText(file);

  });
}

fileInput.addEventListener('change', function(e) {
    var file = e.target.files.item(0);

    if (!file) {
        return;
    }

    readFileJSON(file).then(function(colors) {
       console.log('Colors:', colors);
    });
});

JSBIN: https://jsbin.com/weriguhato/edit?html,js,output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.