68

I am trying to load a text file into my JavaScript file and then read the lines from that file in order to get information, and I tried the FileReader but it does not seem to be working. Can anyone help?

function analyze(){
 var f = new FileReader();
 f.onloadend = function(){
 console.log("success");
 }
 f.readAsText("cities.txt");
}
asked Dec 4, 2012 at 18:27
1

7 Answers 7

65

Yeah it is possible with FileReader, I have already done an example of this, here's the code:

<!DOCTYPE html>
<html>
 <head>
 <title>Read File (via User Input selection)</title>
 <script type="text/javascript">
 var reader; //GLOBAL File Reader object for demo purpose only
 /**
 * Check for the various File API support.
 */
 function checkFileAPI() {
 if (window.File && window.FileReader && window.FileList && window.Blob) {
 reader = new FileReader();
 return true; 
 } else {
 alert('The File APIs are not fully supported by your browser. Fallback required.');
 return false;
 }
 }
 /**
 * read text input
 */
 function readText(filePath) {
 var output = ""; //placeholder for text output
 if(filePath.files && filePath.files[0]) { 
 reader.onload = function (e) {
 output = e.target.result;
 displayContents(output);
 };//end onload()
 reader.readAsText(filePath.files[0]);
 }//end if html5 filelist support
 else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
 try {
 reader = new ActiveXObject("Scripting.FileSystemObject");
 var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
 output = file.ReadAll(); //text contents of file
 file.Close(); //close file "input stream"
 displayContents(output);
 } catch (e) {
 if (e.number == -2146827859) {
 alert('Unable to access local files due to browser security settings. ' + 
 'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' + 
 'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"'); 
 }
 } 
 }
 else { //this is where you could fallback to Java Applet, Flash or similar
 return false;
 } 
 return true;
 } 
 /**
 * display content using a basic HTML replacement
 */
 function displayContents(txt) {
 var el = document.getElementById('main'); 
 el.innerHTML = txt; //display output in DOM
 } 
</script>
</head>
<body onload="checkFileAPI();">
 <div id="container"> 
 <input type="file" onchange='readText(this)' />
 <br/>
 <hr/> 
 <h3>Contents of the Text file:</h3>
 <div id="main">
 ...
 </div>
 </div>
</body>
</html>

It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but (削除) its been a while so I'll have to dig it up (削除ここまで) I've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit). Hope it helps.

Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:

<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>Read File (via AJAX)</title>
<script type="text/javascript">
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
function loadFile() {
 reader.open('get', 'test.txt', true); 
 reader.onreadystatechange = displayContents;
 reader.send(null);
}
function displayContents() {
 if(reader.readyState==4) {
 var el = document.getElementById('main');
 el.innerHTML = reader.responseText;
 }
}
</script>
</head>
<body>
<div id="container">
 <input type="button" value="test.txt" onclick="loadFile()" />
 <div id="main">
 </div>
</div>
</body>
</html>
answered Dec 4, 2012 at 18:38
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the post! However, there’s something I don’t understand: why isn’t reader or this used instead of e.target while they all refer to the FileReader object: demo .
For "this" keyword, really just a personal preference thing, unless its inline on an element I don't bother with it much... tech.pro/tutorial/1192/avoiding-the-this-problem-in-javascript As for "reader", yeah that's a valid point it could be, but again, prefer not use an item in a way that "reads" confusingly. If there's multiple ways to refer to an object, I'd say go for the one you're most comfortable with reading later on.
16

Javascript doesn't have access to the user's filesystem for security reasons. FileReader is only for files manually selected by the user.

NullUserException
85.8k31 gold badges212 silver badges239 bronze badges
answered Dec 4, 2012 at 18:31

1 Comment

This is assuming that OP is talking about a file on the clients computer. If it's something available on the server then it can be loaded in via AJAX.
14

This can be done quite easily using javascript XMLHttpRequest() class (AJAX):

function FileHelper()
{
 FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
 {
 var request = new XMLHttpRequest();
 request.open("GET", pathOfFileToReadFrom, false);
 request.send(null);
 var returnValue = request.responseText;
 return returnValue;
 }
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
answered Mar 3, 2014 at 16:05

1 Comment

I don't understand this, inside the function FileHelpef you are setting a static property of FileHelpef itself, then right away calling the method, but if the function FileHelper itself was never called, then the static property was never set, shouldn't that all be outside the function?
6

(fiddle: https://jsfiddle.net/ya3ya6/7hfkdnrg/2/ )

  1. Usage

Html:

<textarea id='tbMain' ></textarea>
<a id='btnOpen' href='#' >Open</a>

Js:

document.getElementById('btnOpen').onclick = function(){
 openFile(function(txt){
 document.getElementById('tbMain').value = txt; 
 });
}
  1. Js Helper functions
function openFile(callBack){
 var element = document.createElement('input');
 element.setAttribute('type', "file");
 element.setAttribute('id', "btnOpenFile");
 element.onchange = function(){
 readText(this,callBack);
 document.body.removeChild(this);
 }
 element.style.display = 'none';
 document.body.appendChild(element);
 element.click();
}
function readText(filePath,callBack) {
 var reader;
 if (window.File && window.FileReader && window.FileList && window.Blob) {
 reader = new FileReader();
 } else {
 alert('The File APIs are not fully supported by your browser. Fallback required.');
 return false;
 }
 var output = ""; //placeholder for text output
 if(filePath.files && filePath.files[0]) { 
 reader.onload = function (e) {
 output = e.target.result;
 callBack(output);
 };//end onload()
 reader.readAsText(filePath.files[0]);
 }//end if html5 filelist support
 else { //this is where you could fallback to Java Applet, Flash or similar
 return false;
 } 
 return true;
}
answered Mar 10, 2019 at 15:07

Comments

4

my example

<html>
<head>
 <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
 <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
 <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
 <script>
 function PreviewText() {
 var oFReader = new FileReader();
 oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
 oFReader.onload = function(oFREvent) {
 document.getElementById("uploadTextValue").value = oFREvent.target.result;
 document.getElementById("obj").data = oFREvent.target.result;
 };
 };
 jQuery(document).ready(function() {
 $('#viewSource').click(function() {
 var text = $('#uploadTextValue').val();
 alert(text);
 //here ajax
 });
 });
 </script>
 <object width="100%" height="400" data="" id="obj"></object>
 <div>
 <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
 <input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
 </div>
 <a href="#" id="viewSource">Source file</a>
</body>
</html>
Paaarth
4,4693 gold badges27 silver badges39 bronze badges
answered Feb 19, 2015 at 11:15

Comments

3

This is an old question but I think in 2022 there are ES6 ways to handle this:

const $node = document.getElementById('output')
const $file = document.getElementById('file')
const processTextByLine = text => {
 const arr = text.split(/\r?\n/gm)
 arr.map(line => console.log(line))
}
const openFile = event => {
 const input = event.target
 if (!input) throw new Error('null input')
 const [first] = input.files
 const reader = new FileReader()
 reader.onload = () => {
 const text = reader.result
 $node.innerText = text
 
 processTextByLine(text)
 }
 
 reader.readAsText(first)
}
$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
 ...
</div>

If your file is encoded using UTF-8 then we can make an async call using Blob.text()

const $node = document.getElementById('output')
const $file = document.getElementById('file')
const processTextByLine = text => {
 const arr = text.split(/\r?\n/gm)
 arr.map(line => console.log(line))
}
const openFile = async event => {
 const input = event.target
 if (!input) throw new Error('null input')
 const [file] = input.files
 const text = await file.text()
 $node.innerText = text
 processTextByLine(text)
}
$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
 ...
</div>

Note:

processTextByLine() function is not needed, it just shows a case if we need to process the file line by line.

answered Sep 28, 2022 at 1:11

Comments

0

This is the simplest method I have found.

HTML:

<input type="file" id="upload">

JS:

const inputElement = document.getElementById('upload')
inputElement.addEventListener('change', (e) => {
 if (!inputElement.files?.[0]) return
 const reader = new FileReader()
 reader.onload = (e) => {
 console.log(e.target.result)
 }
 reader.readAsText(inputElement.files[0])
})
answered Apr 18, 2023 at 9:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.