0

I have file input and a submit button. The file that will be uploaded contains a json that needs to be loaded in the view, (a graph display). I don't need to store the file, just visualize it.

Is there a way to do this using just jquery, javascript or angular? this application is included as static content inside a Spring app, but has to function as a standalone app also.

Actually I can load a file from the server or make a request to a rest endpoint, but i need to add the option to load a local file with the json data.

Thanks in advance

aruiz
  • 165
  • 1
  • 11
  • Did you try with FileReader (https://developer.mozilla.org/en/docs/Web/API/FileReader)? – Mindastic Jul 14 '15 at 14:22
  • In Angular there is solution that may help: http://stackoverflow.com/questions/17063000/ng-model-for-input-type-file – changtung Jul 14 '15 at 15:40
  • @Mindastic I was looking for other options outside html5, but this have to work for now. – aruiz Jul 14 '15 at 18:25
  • @cyan It's an alternative, but it also relays on the FileReader. Thx Anyway! I'll move to angular shortly so this is going to be usefull – aruiz Jul 14 '15 at 18:27

1 Answers1

2

This will work for IE >= 10. Be aware that there is no fault handling implemented. I'll leave that up to you ;)

HTML:

<input type="file" id="file" name="file">
<button type="submit" id="button">Click!</button>

JS (jQuery):

$('#button').on('click', function() {
    var reader = new FileReader();
    var file = $('#file').get(0).files[0];
    reader.onload = function(e) {
        console.log(JSON.parse(e.target.result));
    };
    reader.readAsText(file);
});
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • I'm gonna try this alternative. This is html5 right? I was looking for something that preferably works on ie8+ but i think its going to be hard. – aruiz Jul 14 '15 at 16:34
  • This is indeed HTML5. Support for IE < 10 should be done with activeX, but as I love to say: `developers should not dwell in the past` – Poul Kruijt Jul 14 '15 at 17:56
  • It worked!, how can you do this on a button click and not when the file is selected? – aruiz Jul 14 '15 at 18:24
  • I've updated my answer (it is untested code, but you get the idea ;) ) – Poul Kruijt Jul 14 '15 at 19:40