Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  134] [ 2]  / answers: 1 / hits: 38557  / 14 Years ago, thu, november 4, 2010, 12:00:00

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>

More From » html

 Answers
22

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>

[#95072] Wednesday, November 3, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madalyngriseldas

Total Points: 167
Total Questions: 92
Total Answers: 85

Location: Iceland
Member since Sat, Sep 17, 2022
2 Years ago
;