Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  128] [ 6]  / answers: 1 / hits: 37147  / 13 Years ago, thu, april 21, 2011, 12:00:00

I have tried using the below code modified from http://www.html5rocks.com/tutorials/file/dndfiles/ to read in a text or xml file and display the contents below.



<!DOCTYPE html> 
<html>
<head>
<title>reading xml</title>
<meta http-equiv=Content-Type content=text/html; charset=utf-8 />
</head>
<body>
<input type=file id=files name=files[] multiple />
<output id=list></output>

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

// Loop through the FileList
for (var i = 0, f; f = files[i]; i++) {

var reader = new FileReader();

// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Print the contents of the file
var span = document.createElement('span');
span.innerHTML = ['<p>',e.target.result,'</p>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);

// Read in the file
//reader.readAsDataText(f,UTF-8);
reader.readAsDataURL(f);
}
}

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




reader.readAsDataText(f,UTF-8); Does not work



reader.readAsDataURL(f); Displays the file in Base64



How can I get a text file to be displayed on the page?


More From » file

 Answers
39

You need to pass in the encoding as a string; put quotes around the UTF-8. Also, it's readAsText, not readAsDataText:



reader.readAsText(f,UTF-8);


Or you can just leave the encoding off entirely, in which case it will try to auto-detect UTF-16BE or LE, and if it's not one of those, it will just use UTF-8 by default.



reader.readAsText(f);

[#92633] Monday, April 18, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cristinadomoniquel

Total Points: 320
Total Questions: 94
Total Answers: 94

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
cristinadomoniquel questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Mon, Aug 17, 20, 00:00, 4 Years ago
;