I have a html code like this:
<input type="file" id="up" />
<input type="submit" id="btn" />
And I have a JSON file like this:
{
"name": "John",
"family": "Smith"
}
And a simple JavaScript function:
alert_data(name, family)
{
alert('Name : ' + name + ', Family : '+ family)
}
Now I want to call alert_data()
with name and family that stored in JSON file which uploaded using my HTML input.
Is there any way using an HTML5 file reader or something else?
I'm not using server side programming, all of them are client side.
You will need an HTML5 browser, but this is possible.
(function(){
function onChange(event) {
var reader = new FileReader();
reader.onload = onReaderLoad;
reader.readAsText(event.target.files[0]);
}
function onReaderLoad(event){
console.log(event.target.result);
var obj = JSON.parse(event.target.result);
alert_data(obj.name, obj.family);
}
function alert_data(name, family){
alert('Name : ' + name + ', Family : ' + family);
}
document.getElementById('file').addEventListener('change', onChange);
}());
<input id="file" type="file" />
<p>Select a file with the following format.</p>
<pre>
{
"name": "testName",
"family": "testFamily"
}
</pre>
</div>
Yep! It can be done with HTML5 FileReader. And it's actually pretty simple.
Save the json as a .js file and load it in my example
{
"name": "John",
"family": "Smith"
}
This is where the magic happens:
$("#up").change(function(event){
var uploadedFile = event.target.files[0];
if(uploadedFile.type !== "text/javascript" && uploadedFile.type !== "application/x-javascript") {
alert("Wrong file type == " + uploadedFile.type);
return false;
}
if (uploadedFile) {
var readFile = new FileReader();
readFile.onload = function(e) {
var contents = e.target.result;
var json = JSON.parse(contents);
alert_data(json);
};
readFile.readAsText(uploadedFile);
} else {
console.log("Failed to load file");
}
});
function alert_data(json)
{
alert('Name : ' + json.name + ', Family : '+ json.family)
}
Fiddle link with this code: http://jsfiddle.net/thomas_kingo/dfej7p3r/3/
(The uploadedFile.type check is only tested in Chrome and firefox)
Here's a shorthand version of Sam Greenhalghs answer that works for me.
$(document).on('change', '.file-upload-button', function(event) {
var reader = new FileReader();
reader.onload = function(event) {
var jsonObj = JSON.parse(event.target.result);
alert(jsonObj.name);
}
reader.readAsText(event.target.files[0]);
});
<input class='file-upload-button' type="file" />
</div>