Edit and save a file locally with JS

前端 未结 3 645
鱼传尺愫
鱼传尺愫 2020-12-19 14:09

I don\'t know if it\'s possible but here\'s what I would like to achieve. I would want to be able to load a JSON file using a file input, edit it in a web page and then save

相关标签:
3条回答
  • 2020-12-19 14:45

    Consider looking into FileSystem. It's only in Chrome at present and not likely to be supported in other browsers.

    0 讨论(0)
  • 2020-12-19 14:56

    var input = document.querySelector("input[type=file]");
    var text = document.querySelector("textarea");
    var button = document.querySelector("input[type=button]");
    var name;
    
    input.onchange = function(e) {
      var reader = new FileReader();
      reader.onload = function(event) {
        text.value = event.target.result;
        button.disabled = false;
      }
      name = e.target.files[0].name;
      reader.readAsText(new Blob([e.target.files[0]], {
        "type": "application/json"
      }));
    }
    
    button.onclick = function(e) {
      e.preventDefault();
      var blob = new Blob([text.value], {
        "type": "application/json"
      });
      var a = document.createElement("a");
      a.download = name;
      a.href = URL.createObjectURL(blob);
      document.body.appendChild(a);
      a.click();
      text.value = "";
      input.value = "";
      button.disabled = true;
      document.body.removeChild(a);
    }
    textarea {
      white-space: pre;
      width: 400px;
      height: 300px;
    }
    <form>
      <input type="file" />
      <br />
      <textarea></textarea>
      <br />
      <input type="button" disabled="true" value="Save" />
    </form>

    0 讨论(0)
  • 2020-12-19 15:01

    Locale storage? Stores key value pairs that will persist -variable limitations across browsers, but the general idea is supported by Chrome, Firefox, Safari, Opera, IE. Things are stored as strings, so you could store json type information as a value, rather than breaking your json into lots of key/value items.

    This is not the most secure way of doing this, but would probably be fine for preferences and even application state, if you don't mind there being a potential for something client side to tweak values.

    If a user wants to save this, then you invoke the download/save file option.

    0 讨论(0)
提交回复
热议问题