Skip to content Skip to sidebar Skip to footer

Uploading A Json File And Using It

How can I upload a JSON file on some click on a button on my web page say 'import', and use it to store in a variable to use and update it using JavaScript. I have gone through the

Solution 1:

Without server side code, your best approach may be to provide a textarea element for the user to copy/paste the JSON into, and then parse it using JSON.parse.

You could even go as far as to use something like Ace Editor to provide syntax highlighting for JSON - you can see it in action on the Ace Editor Kitchen Sink Demo - select JSON from the dropdown list in the top left.


Edit:

Turns out I was wrong. Here is a fiddle demonstrating the FileReader in use, which is exactly what you need:

https://jsfiddle.net/Ln37kqc0/

Here is the code:

Javascript:

document.getElementById('import').onclick = function() {
    var files = document.getElementById('selectFiles').files;
  console.log(files);
  if (files.length <= 0) {
    returnfalse;
  }

  var fr = newFileReader();

  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));
};

HTML:

<input type="file"id="selectFiles" value="Import" /><br />
<button id="import">Import</button>
<textarea id="result"></textarea>

Solution 2:

I have got a way to use the uploaded json file, here is the way i found.

$("#inputFile").change(function(e) {
    onChange(e);
});

functiononChange(event) {
    var reader = newFileReader();
    reader.onload = onReaderLoad;
    reader.readAsText(event.target.files[0]);
}

functiononReaderLoad(event){
    //alert(event.target.result);var obj = JSON.parse(event.target.result);
    alert(obj);
}

Solution 3:

Basic upload File:

    <inputid="contentFile"type="file" accept="application/json" />
document.getElementById('contentFile').onchange = function(evt) {
        try {
            let files = evt.target.files;
            if (!files.length) {
                alert('No file selected!');
                return;
            }
            let file = files[0];
            let reader = newFileReader();
            const self = this;
            reader.onload = (event) => {
                console.log('FILE CONTENT', event.target.result);
            };
            reader.readAsText(file);
        } catch (err) {
            console.error(err);
        }
    }

Solution 4:

Try this, works perfect

handleUploadFile = async(doc) => {
  let file = doc.target.files[0]
  let reader = new FileReader(file)

  // await reader.readAsDataURL(file)

  reader.readAsText(file)

  reader.onload = async(e) => {

    let aaa = e.target.result

    let content = await JSON.parse(aaa)
    console.log(content)

  }
}

Solution 5:

You may want to add the draggable option

Firs create your HTML

<divclass="drag"id="drag_area"><inputclass="box_file disabled"type="file"name="files[]"id="file"data-multiple-caption="{count} files selected"multiple /><labelfor="file"><strong>Choose save file</strong><spanclass="box__dragndrop"> or drag it here</span>.</label></div>

Than write out your JS

$("#drag_area").on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
    e.preventDefault();
    e.stopPropagation();
})
.on('dragover dragenter', function () {
    $("#drag_area").addClass('dr_active');
    // this is needed if you wish to style your drag area on drag events
})
.on('dragleave dragend drop', function () {
    $("#drag_area").removeClass('dr_active');
    // this is needed if you wish to style your drag area on drag events
})
.on('drop', function (e) {
    let droppedFiles = e.originalEvent.dataTransfer.files;
    let reader = newFileReader()
    reader.readAsDataURL(droppedFiles[0])
    reader.onloadend = function () {
    $.ajax({
        url: reader.result,
        success: function (data) {
          console.log(JSON.parse(data)); // This is your JSON
        },
        error: function (request, error) {
            cliLog(2, "Upload", "Cant upload save file")
        }
    });
}
}),

Post a Comment for "Uploading A Json File And Using It"