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

后端 未结 1 1995
盖世英雄少女心
盖世英雄少女心 2021-02-11 04:25

I\'m just trying on the task, file manipulation system using java script. As I was referred from W3C File API( https://www.w3.org/TR/FileAPI/ ), we can only read local files lik

相关标签:
1条回答
  • 2021-02-11 05:10

    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>

    0 讨论(0)
提交回复
热议问题