Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Edit and save a file locally with JS

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 the changes is the initial file. I know that for security reason the browser doesn't have full access to the disk but I was wondering if there was a way to allow updates for a specific file.

In a nutshell, the flow would be

  1. Load the file
  2. Edit it
  3. Save the changes (rewriting the initial one)

I don't care about browser compatibility, so if the solution is based on a specific brower's API, it's good enough for me.

Also, I know about the download attribute, but I'm trying to avoid the "normal" download flow (popup or the file being thrown is the Downloads folder).

Thanks in advance !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...