Set the text file to read in JavaScript?

问题: I am testing out a file reader for one of my html projects. I want the JavaScript program to read a particular file immediately, instead of the file being selected by the u...

问题:

I am testing out a file reader for one of my html projects. I want the JavaScript program to read a particular file immediately, instead of the file being selected by the user (in this case, me). I have the p tag and the id of the tag as 'file'. When I run the program in my browser (Safari), I get the error message

TypeError: Argument 1 ('blob') to FileReader.readAsText must be an instance of Blob

I have been looking all over the internet to find a solution, but I just can't find anything. I was thinking of doing my program with python and then inserting it into my webpage with trinket.io's iframe tag. But then I sort of gave up on that idea. Here is the code:

var reader = new FileReader();
var fileToRead = "quotes.txt";

// attach event, that will be fired, when read is end
reader.addEventListener("loadend", function() {
  document.getElementById('file').innerText = reader.result;
});

reader.readAsText(fileToRead);

I would like the output of this program to show the contents of the text file, yet when I run it in my browser it gives me a blank screen. I hope there is a solution out there.


回答1:

The FileReader expects a blob - which is a file-like object. It can be a blob stored in the memory or a reference to a file. For security reasons, it doesn't work with file names - you can't simply read an arbitrary file from the user's file system without his consent.

To achieve it with the user's consent, keep reading below.

You'll need the user to use a file input to explicitly select a file. Once a file is selected, the input will trigger an event with a FileList, containing references to the selected files. The file references can then be used in the FileReader to read their contents.

Here's a working example:

  fileInput.addEventListener("change", onFileChanged)
  
  function onFileChanged(event) {
    const fileList = event.target.files
    fileText.value = ""

    if (fileList.length === 0) {
      console.log("No file selected, please select one!")
      return
    }
    
    if (fileList.length > 1) {
      console.log("Too many files selected, please select only one!")
      return
    }
    
    // destruct first entry of fileList, equivalent to `const file = fileList[0]`
    const [file] = fileList
    
    // you can validate what type of file you accept
    if (file.type !== "text/plain") {
      console.log("Only text files are supported!")
      return
    }

    console.log("Reading file", file.name)
    readFile(file, printText)
  }
  
  function readFile(file, callback) {
    if (typeof callback !== "function") {
      throw new Error("Please supply a callback function to handle the read text!")
    }
    const reader = new FileReader()
    reader.addEventListener("load", function() {
      callback(reader.result)
    })
    return reader.readAsText(file)
  }
  
  function printText(text) {
    fileText.value = text
  }
<input id="fileInput" type="file"/>

<div>
  <textarea id="fileText" cols="50" rows="10"></textarea>
</div>

  • 发表于 2019-02-19 23:09
  • 阅读 ( 193 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除