2

I want to read a textfile on my local machine and put the contents into a variable. All the examples I've found use an input button (type = "file") that passes an argument that gets scooped up as "evt" by the function. I simply would pass a filename, like "mydata.txt".

I can do it with ajax, but I would like to use it without XAMPP.

function readSingleFile(evt)
{
    var f = evt.target.files[0];

    if (f)
    {
        var r = new FileReader();
        r.onload = function(e)
        { 
            var contents = e.target.result;
            document.getElementById('div1').innerHTML = contents;
        }
        r.readAsText(f);
    }
    else
    {            
        alert("Failed to load file");
    }
}

1 Answer 1

1

AJAX allows you to read a file that resides on the server.

For security reasons, it will never be possible to read an arbitrary path on the client filesystem.
The <input type="file" /> allows the user to select the file, which is why it's safe.

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

4 Comments

I'm a bit confused. I can load a script from my local machine <script type = "text/javascript" src = "jquery-1.9.0.min.js"></script>. I can put all kinds of things in there, like the contents of the textfile. Except it's a chore to format that text the way I want too.
@wubbewubbewubbe: Wrong. That loads a script from the server. It sends an HTTP request to the server in the same path as the file.
Still confused, because it works on my local machine without XAMPP running.
@wubbewubbewubbe: If you open it from disk (as opposed to navigating to it on a local web server), the server and the client will both use the same filesystem. However, the SOP will get in your way if you want to use AJAX.

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.