使用JS在本地编辑和保存文件 [英] Edit and save a file locally with JS

查看:131
本文介绍了使用JS在本地编辑和保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否可能,但这就是我想要实现的目标。我希望能够使用文件输入加载JSON文件,在网页中编辑它,然后保存更改是初始文件。我知道出于安全原因,浏览器没有对磁盘的完全访问权限,但我想知道是否有办法允许更新特定文件。

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简而言之,流程将是

In a nutshell, the flow would be


  1. 加载文件

  2. 编辑

  3. 保存更改(重写初始更改)

我不关心浏览器兼容性,所以如果解决方案基于特定的浏览器API,对我来说已经足够了。

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).

提前致谢!

推荐答案

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>

这篇关于使用JS在本地编辑和保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆