I am novice in File API. At the moment I have a task to execute data from json-file using File API and drag-and-drop method. JSON-file example:
[
{
"id":2,
"name":"VoffCafe",
"coordinates":{
"latitude":56.629418,
"longitude":47.893927
}
}
]
Data from JSON-file must be written to some variables.
Now I have an example, it is sample on my task, but it shows picture, which is dropped on web-page. Script from this example, which does this, below:
<script>
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'File API & FileReader available';
}
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
console.log(event.target);
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
console.log(file);
reader.readAsDataURL(file);
return false;
};
</script>
Full page-example, where this script works is here: http://html5demos.com/file-api
How to redo this script to it be satisfied my demands?
You can brake down the task of a "local JSON file grabber" into 3 main steps:
1: The file selector
The ondrop event operates as our file selector in this example. see documentation here.
2: The Filereader
Javascript's Filereader often confuses people due to its asynchronous nature. Long story short : In the code below the
reader.onload
function is called afterreader.readAsText()
is completed. see documentation here3. The Parser
Once you have a string to parse, turning it into an object is dead simple with
JSON.parse()
. In this example just pass in the file contents withevent.target.result
.putting it all together
I hope that helps!