Uploading a JSON file and using it

后端 未结 5 2047
深忆病人
深忆病人 2020-12-13 16:00

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

相关标签:
5条回答
  • 2020-12-13 16:30

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

    HTML:

    <input type="file" id="selectFiles" value="Import" /><br />
    <button id="import">Import</button>
    <textarea id="result"></textarea>
    
    0 讨论(0)
  • 2020-12-13 16:39

    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)
    
      }
    }
    
    0 讨论(0)
  • 2020-12-13 16:40

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

    $("#inputFile").change(function(e) {
        onChange(e);
    });
    
    function onChange(event) {
        var reader = new FileReader();
        reader.onload = onReaderLoad;
        reader.readAsText(event.target.files[0]);
    }
    
    function onReaderLoad(event){
        //alert(event.target.result);
        var obj = JSON.parse(event.target.result);
        alert(obj);
    }
    
    0 讨论(0)
  • 2020-12-13 16:43

    You may want to add the draggable option

    Firs create your HTML

    <div class="drag" id="drag_area">
            <input class="box_file disabled" type="file" name="files[]" id="file" data-multiple-caption="{count} files selected" multiple />
            <label for="file"><strong>Choose save file</strong><span class="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 = new FileReader()
        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")
            }
        });
    }
    }),
    
    0 讨论(0)
  • 2020-12-13 16:49

    Basic upload File:

        <input id="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 = new FileReader();
                const self = this;
                reader.onload = (event) => {
                    console.log('FILE CONTENT', event.target.result);
                };
                reader.readAsText(file);
            } catch (err) {
                console.error(err);
            }
        }
    
                         ` 
    
    0 讨论(0)
提交回复
热议问题