24

I haven't used JavaScript in a while and I can't seem to read a text file and display the contents.

I've tried onload as well as onloadend. If I just put reader.onload = alert('Hello'); the alert fires, but I can't get anything to work with the function.

Not exactly sure where to go from here. I've tried defining the function after reader.onload = function(evt)... but that doesn't work.

I've tried in Safari 6.0.5 and Chrome as well.

<!DOCTYPE HTML>                                                                    
<html>                                                                             
<head>                                                                         
    <title>Pi to Colors</title>                                                
</head>                                                                        
<body>                                                                         
<script>                                                                       
function readFile() {                                                       
    var reader = new FileReader();                                             
    reader.onload = readSuccess;                                            
    function readSuccess(evt) {                                             
        var field = document.getElementById('main');                        
        field.innerHTML = evt.target.result;                                
    };                                                                      
    reader.readAsText("/pi.txt");                                              
}                                                                           
</script>                                                                      
<div id="main">                                                                

</div>                                                                         
</body>                                                                        
</html> 
2
  • So you're running this code in a browser? Trying to read a local file off your system? I'm pretty sure the browser prevents you from doing that. What does your browser console tell you? Commented Aug 30, 2013 at 23:35
  • The error console does not say anything. Not in Safari. Commented Aug 30, 2013 at 23:41

4 Answers 4

25

You can't grab a local file like that for security reasons.

Another underlying problem is that readAsText (and all the read functions) need the file's content and not its file path/name. You can grab this from the files collection of the input type="file" element. Here is how your code could work:

function readFile(file) {                                                       
    var reader = new FileReader();
    reader.onload = readSuccess;                                            
    function readSuccess(evt) { 
        var field = document.getElementById('main');                        
        field.innerHTML = evt.target.result;                                
    };
    reader.readAsText(file);                                              
} 

document.getElementById('selectedFile').onchange = function(e) {
    readFile(e.srcElement.files[0]);
};

Here is the jsfiddle: http://jsfiddle.net/fstreamz/ngXBV/1/

Note: this code not work in safari browser

Sign up to request clarification or add additional context in comments.

3 Comments

"reader.onload = readSuccess;" Shouldn't 'readSuccess' be 'readSuccess()'?
No, it would assign "undefined" which is the return value of the function.
My variation on this jsfiddle demonstrates my problem, you can't use addEventListener('onload', readSuccess), despite the Mozilla documentation : "Note: As FileReader inherits from EventTarget, all those events can also be listened for by using the addEventListener method."
1

you can use ajax to get the content of your file:

var reader= new XMLHttpRequest();
reader.open('GET', '/pi.txt');
reader.onreadystatechange =readSuccess();
function readSuccess(evt) {                                             
   var field = document.getElementById('main');                        
   field.innerHTML = reader.responseText;                                
};
reader.send();

Comments

0

I have the same the problem and I found a solution. You can't read the local file unless the user has permission. You can put a <input type="file"> on your page. When the file input change, you can read the data.

Comments

-2

Nothing worked for me. Below you can find my ugly solution, but it was the only one that did the job. In my case the user can upload up to 3 files, so the var iPDF can be 0,1,2.

	var iPDF=UpdatedExistingNumberOfPDFfiles;
	if (iPDF < NoMaxPDFfiles) {
		var reader = new FileReader();
		reader.readAsDataURL(files[iPDF-UpdatedExistingNumberOfPDFfiles]);
		reader.onload = function (){
		var PDFdataURL = reader.result;
		var xhr = new XMLHttpRequest();
		xhr.open("POST", "Observation_PDFUpload.php",true);
		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		var NumberOfPDFfile = iPDF+1;
		xhr.send("PDFfileURL="+PDFdataURL+"&PDFfileName="+PDFfileName+"-Annex-"+NumberOfPDFfile);
		iPDF++;
		if (iPDF < NoMaxPDFfiles) {
			reader.readAsDataURL(files[iPDF-UpdatedExistingNumberOfPDFfiles]);
			reader.onload = function (){
			PDFdataURL = reader.result;
			var xhr1 = new XMLHttpRequest();
			xhr1.open("POST", "Observation_PDFUpload.php",true);
			xhr1.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			NumberOfPDFfile = iPDF+1;
			xhr1.send("PDFfileURL="+PDFdataURL+"&PDFfileName="+PDFfileName+"-Annex-"+NumberOfPDFfile);
			iPDF++;	
			if (iPDF < NoMaxPDFfiles) {
			reader.readAsDataURL(files[iPDF-UpdatedExistingNumberOfPDFfiles]);
			reader.onload = function (){
			PDFdataURL = reader.result;
			var xhr2 = new XMLHttpRequest();
			xhr2.open("POST", "Observation_PDFUpload.php",true);
			xhr2.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			NumberOfPDFfile = iPDF+1;
			xhr2.send("PDFfileURL="+PDFdataURL+"&PDFfileName="+PDFfileName+"-Annex-"+NumberOfPDFfile);
			}	
			}			
		
			}
		}
		}
		};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.