如何编写Javascript来从文本字段加载/写入来自/到磁盘的文件

时间:2016-01-05 02:55:46

标签: javascript google-chrome io hard-drive

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

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

最诚挚的问候 /拉塞

2 个答案:

答案 0 :(得分:1)

尝试使用input type="file" accepts MIME类型设置为"text/plain"textareaa元素,download属性,{{1} },FileReader协议,data:



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




答案 1 :(得分:1)

对你的问题的完整答案非常冗长,如此简短:

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

<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';
}