Edit and save a file locally with JS

前端 未结 3 663
鱼传尺愫
鱼传尺愫 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: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;
    }


提交回复
热议问题