File manipulations such as Read/Write local files using Javascript without server

两盒软妹~` 提交于 2019-12-03 09:01:17

In your code, it's not reading from the local file (test.txt), it's sending Ajax GET request to server and read file in server side.

To read local file (files that stored in machine where browser is installed), you need to use FileAPI, which is not used in current code.

To write file to local, it's impossible to write it directly using JavaScript. Otherwise, it would be a huge security vulnerability. However, you can generate a URL from File object, and use that URL as the href attribute of <a> tag, so that user can download and "write to local" manually.

Here is a code snippet to read & "write" local file:

var inputElement = document.getElementById("input");
var reader = new FileReader();
var downloadLink = document.getElementById('downloadLink');

reader.onloadend = function(){
  console.log(reader.result);
}
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  var fileSelected = this.files[0]; /* now you can work with the file list */
  reader.readAsBinaryString(fileSelected);
  downloadLink.href = window.URL.createObjectURL(fileSelected);
}
<input type="file" id="input">
<a id="downloadLink" download>Download</a>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!