Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  14] [ 1]  / answers: 1 / hits: 39893  / 12 Years ago, tue, september 11, 2012, 12:00:00

I've written the following code in an attempt to read the contents of a .txt file



<!DOCTYPE html>
<html>

<input type=file id=files name=file />
<div id=container style=height: 500px; min-width: 500px></div>

<script>
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object

// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{

var reader = new FileReader();
reader.onload = (function(theFile)
{
var contents = theFile.target.result;
var lines = contents.split('n');

})(f);

reader.readAsText(f);
}
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</html>


Using firebug I set a break on var contents = theFile.target.result; but nothing is being returned. Can anyone spot what's wrong?



Thank you


More From » html

 Answers
78

Try (onload with closure):



function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object

// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{

var reader = new FileReader();
reader.onload = (function(reader)
{
return function()
{
var contents = reader.result;
var lines = contents.split('n');
//////
document.getElementById('container').innerHTML=contents;
}
})(reader);

reader.readAsText(f);
}
}


Or (without closure):



function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object

// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{

var reader = new FileReader();
reader.onload = function(event)
{
// NOTE: event.target point to FileReader
var contents = event.target.result;
var lines = contents.split('n');
//////
document.getElementById('container').innerHTML=contents;
};

reader.readAsText(f);
}
}

[#83134] Monday, September 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nolancampbellc

Total Points: 9
Total Questions: 102
Total Answers: 101

Location: Saint Vincent and the Grenadines
Member since Mon, Jan 16, 2023
1 Year ago
;