Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read local text file with javascript [duplicate]

Tags:

javascript

I want to read a local text file from my local html file, so I tried to follow the solution in this thread Javascript - read local text file but the suggested solution does not work for me either:

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

When I call the function readTextFile("file:///D:/test/text.txt"); no error does show up in firebug but no alert is shown neither. I use Windows und Firefox 51.0.1 (64-Bit). I don't want to use the function FileReader() in combination with a button <input type='file' onchange='openFile(event)' ... since the text file needs to be read automatically when loading the page. So how can I make work the solution above?

Reading the thread linked it looks like others also have problems with that solution although the thread is marked as solved.

like image 804
Markus Avatar asked Dec 14 '22 00:12

Markus


1 Answers

Complete HTML and JavaScript file as an example for reading client side data files. Client side files can only be accessed by the FileReader, specifying a user selected file.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
                function loadFile(o)
                {
                    var fr = new FileReader();
                    fr.onload = function(e)
                        {
                            showDataFile(e, o);
                        };
                    fr.readAsText(o.files[0]);
                }

                function showDataFile(e, o)
                {
                    document.getElementById("data").innerText = e.target.result;
                }
            </script>

        </script>
    </head>
    <body>
        Select file to read <input type="file" onchange="loadFile(this)">
        <pre id="data"></pre>
    </body>
</html>
like image 193
Balazs Vago Avatar answered Dec 31 '22 12:12

Balazs Vago