67

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");
}
Alex
  • 163
  • 7
CRS
  • 827
  • 2
  • 13
  • 20
  • 6
    Read: http://www.html5rocks.com/en/tutorials/file/dndfiles/. If it's a local file, the user has to select the file itself for security reasons. Related: http://stackoverflow.com/questions/13428532/using-a-local-file-as-a-data-source-in-javascript – NullUserException Dec 04 '12 at 18:29

7 Answers7

64

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>
bcmoney
  • 2,889
  • 1
  • 24
  • 30
  • 1
    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](http://jsfiddle.net/Mori/tJBHZ/)**. – Mori May 20 '14 at 09:45
  • 2
    For "this" keyword, really just a personal preference thing, unless its inline on an element I don't bother with it much... http://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. – bcmoney May 26 '14 at 20:51
15

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" );
Community
  • 1
  • 1
user3375451
  • 187
  • 1
  • 2
  • 1
    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? – B''H Bi'ezras -- Boruch Hashem Oct 12 '20 at 03:37
14

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

NullUserException
  • 83,810
  • 28
  • 209
  • 234
Meliborn
  • 6,495
  • 6
  • 34
  • 53
  • 5
    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. – Mike Cluck Dec 04 '12 at 18:36
5

(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;
}
yaya
  • 7,675
  • 1
  • 39
  • 38
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>
Parth Raval
  • 4,097
  • 3
  • 23
  • 36
websky
  • 3,047
  • 1
  • 33
  • 31
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.

Teocci
  • 7,189
  • 1
  • 50
  • 48
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])
})
Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76