Search code examples
javascriptfilefile-upload

Preview for uploaded Json file content


I need to display the Json contents to the textbox from uploaded Json file.

my HTML code,

<input type="file" value="Import" name="myFiles" onchange="metadataFile()"/><br />
<textarea id="result">  
</textarea>

my JavaScript Code,

window.metadataFile = function() {
    var files = document.getElementsByName('myFiles').files;
    console.log(files);
    if (files.length <= 0) {
        return false;
    }  
    var fr = new FileReader();  
    fr.onload = function(e) { 
       console.log(e);
       var result = JSON.parse(e.target.result);
       var formatted = JSON.stringify(result, null, 2);
       document.getElementById('result').value = formatted;
    }  
    fr.readAsText(files.item(0));
}

jsfiddle link : https://jsfiddle.net/magendiran/zbjpL6rf/


Solution

  • Please note that getElementsByName returns a collection of elements that match the search name attribute, and not a single element.

    There is an error in your script, which prevent it from being execute properly since you expect getElementsByName to return a single element and not a collection.

    window.metadataFile = function() {
        var files = document.getElementsByName('myFiles')[0].files;
        ...
        ...
    }