【问题标题】:How write Javascript for loading/writing contet from text-field from/to disk如何编写 Javascript 以从/向磁盘加载/写入文本字段中的内容
【发布时间】:2016-04-08 19:03:01
【问题描述】:

如何使用带有按钮的输入文本字段,让用户在使用 Chrome 时从硬盘驱动器中选择一个 .txt 文件,并提供将文本字段中的内容存储到硬盘驱动器的选项。

我怎样才能用纯 Javascript 做到这一点?

最诚挚的问候 /拉斯

【问题讨论】:

  • 由于security reasons,您无法从客户端代码中访问文件系统。除非您正在谈论开发 Chrome 插件,但我没有看到您提到这一点。您可以试试File System API,但它的支持很差,而且我不确定它的功能,因为我从未使用过它。
  • 好的,但我想询问/让用户选择从磁盘加载或保存到磁盘,不要强迫用户。不能有弹窗查询吗?
  • 您可以使用拖放或文件输入加载文本文件,但无法保存。您可能想查看可以保存数据或使用服务器处理存储的 localStorage
  • 不,它不是插件,我只是一个写考试的初学者,想添加一个额外的功能。没有插件,就是普通的网页..
  • @Lasse Karagiannis 查看更新的评论。但据我所知,这是主要的安全问题之一,而且不太可能以这种方式实施。您可以做的最好的事情是要求用户将文件上传到您的服务器并让他们下载生成的文件。但是您将无法像使用 C、Java 或类似语言一样打开和写入文件。

标签: javascript google-chrome io hard-drive


【解决方案1】:

尝试使用input type="file",将accepts MIME类型设置为"text/plain"textareaa元素,download属性,FileReaderdata:协议,encodeURIComponent

var input = document.querySelector("input");
var text = document.querySelector("textarea");
var button = document.querySelector("button");
var name;

input.onchange = function() {
  name = this.files[0].name;
  var reader = new FileReader();
  reader.onload = function() {
    text.value = this.result
  }
  reader.readAsText(this.files[0])
}

button.onclick = function() {
  var a = document.createElement("a");
  // `"data:text/plain," + text.value` : new file
  a.href = "data:text/plain;charset=utf-8," + encodeURIComponent(text.value);
  a.download = name ||  "file-" + new Date().getTime();
  document.body.appendChild(a);
  // creates `"Save file"` dialog
  a.click();
  document.body.removeChild(a)
}
<input type="file" accepts="text/plain"/><br>
<textarea width="300px" height="200px">
</textarea><br>
<button>save</button>

【讨论】:

【解决方案2】:

你的问题的完整答案会很长,所以简短:

使用输入类型为文件的表单,允许用户输入文件:

<form>Select file: <input type="file" id="loadfile"/></form>

使用 javascript,通过侦听提交事件、单击事件或更改事件来对设置的值做出反应。此处的示例着眼于更改事件。

var input = document.getElementById('loadfile');
input.onchange = function handleInputFileChanged(event) {
  var files = event.target.files;
  if(!files || !files.length) {
    return;
  }
  importFiles(files);
};

function importFiles(files) {
  // Read in the contents of the files as text and process them here

  var numFiles = files.length;
  var filesProcessed = 0;
  for(var i = 0; i < numFiles; i++) {
    processFile(files[i]);
  }

  function processFile(file) {
    var reader = new FileReader();
    reader.onload = function() {
      filesProcessed++;

      // do something with the file text, here i am just printing 
      // it to the browser console
      var contentString = reader.result;
      console.log('File text: %s', contentString);

      if(filesProcessed === numFiles) allFilesRead();
    };
    reader.onerror = function() {
      filesProcessed++;
      if(filesProcessed === numFiles) allFilesRead();
    };
    reader.readAsText(file);
  }

  function allFilesRead() {
    // do something now that all files have been read
  }
}

要保存到文件,只需向用户提供提示即可完成。例如:

<form><button id="savebutton" value="Save"></form>

在脚本中,监听按钮点击事件,然后开始下载:

var button = document.getElementById('savebutton');
button.onclick = function(event) {
  var content = getContentToSaveAsString();


  // to automatically start a download, we are going to create a 
  // hidden anchor element, then pseudo-click it

  // Create the anchor and sets its href to a data uri
  var anchor = document.createElement('a');
  var blob = new Blob([content], {type: 'text/plain'});
  var objectURL = URL.createObjectURL(blob);
  anchor.href = objectURL;
  anchor.setAttribute('download', 'defaultfilenamegoeshere.txt');

  // attach the hidden anchor to the page
  anchor.style.display = 'none';
  document.body.appendChild(anchor);

  // this starts the download, the user will get a prompt of where to 
  // save or if in chrome it just starts downloading to download 
  // folder, just as if they had right clicked on an anchor in 
  // the page and selected Save Target As
  anchor.click();

  // remove our temporary anchor element, cleaning up after ourselves
  URL.revokeObjectURL(objectURL);
  anchor.remove();
};

function getContentToSaveAsString() {
  // Create and return a string here that will be saved to a
  // text file when the user clicks the save button
  return 'string of stuff';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多