Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

html - Chrome FileReader

Can someone give me an example of using the FileReader API go get contents of a file in chrome?

It seems to be returning undefined for me.

<!doctype html>
<html>
<script>
function handle_files(files) {
  console.log(files)
  reader = new FileReader()
  ret = []
  for (i = 0; i < files.length; i++) {
    file = files[i]
    console.log(file)
    text = reader.readAsText(file) //readAsdataURL
    console.log(text) //undefined
    ret.push(text)
  }
  console.log(ret) // [undefined]

}
</script>
<body>
FileReader Test
<input type="file" onchange="handle_files(this.files)">
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My problem was that I assumed FileReader was sychronous. Here is the right way to do it. If you are on chrome, this code has to be running on a server (localhost or on a site). It won't work with a local file.

<!doctype html>
<html>
<script>
function handle_files(files) {
  for (i = 0; i < files.length; i++) {
    file = files[i]
    console.log(file)
    var reader = new FileReader()
    ret = []
    reader.onload = function(e) {
      console.log(e.target.result)
    }
    reader.onerror = function(stuff) {
      console.log("error", stuff)
      console.log (stuff.getMessage())
    }
    reader.readAsText(file) //readAsdataURL
  }

}
</script>
<body>
FileReader that works!
<input type="file" multiple onchange="handle_files(this.files)">
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...