2

On click of a button called result, I want to read and display a text file (which is present in my local drive location say: C:\test.txt) using Javascript function and display the test.txt file contents in a HTML text area.

I am new to Javascript,can anyone suggest the code for Javascript function to read and display the contents of .txt file?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dojo_user
  • 281
  • 4
  • 9
  • 28

4 Answers4

7

An Ajax request to a local file will fail for security reasons.

Imagine a website that accesses a file on your computer like you ask, but without letting you know, and sends the content to a hacker. You would not want that, and browser makers took care of that to protect your security!

To read the content of a file located on your hard drive, you would need to have a <input type="file"> and let the user select the file himself. You don't need to upload it. You can do it this way :

<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var result = document.getElementById("result");

  reader.onload = function(event) {
    result.innerHTML = event.target.result;
  };

  reader.readAsText(selectedFile);
}

JS Fiddle

blex
  • 24,941
  • 5
  • 39
  • 72
  • I think you got my question wrong. See here I want to provide the path of my text file(present in local drive say C:\text.txt or any) so that onclick of the button, it should read the text file from local disk and display the contents in the text area.Currently the code provides us a scope to manually browse and upload the file and display the contents in it. But what i want is it should display the content on button click action. – Dojo_user May 18 '14 at 18:42
  • @Dojo_user : I did understand your question correctly, but what you are asking is totally impossible in javascript due to browser security rules. And by the way, I do not upload the file, I just let the user select it, as required by browsers, then I display it. Believe me, I've tried before. You might have a solution with Flash. Please see [**this**](http://stackoverflow.com/questions/1696877/how-to-set-a-value-to-a-file-input-in-html#answer-1696884). – blex May 18 '14 at 19:35
  • 1
    Actually, Flash would also require the user to select the file. You don't have any other alternative. [See this](http://stackoverflow.com/questions/1811736/can-flash-action-script-read-and-write-local-file-system#answer-1811836). – blex May 18 '14 at 19:50
3

Using $.ajax() function: http://api.jquery.com/jQuery.ajax/

$(function(){
    $.ajax({
        url: "pathToYourFile",
        async: false,   // asynchronous request? (synchronous requests are discouraged...)
        cache: false,   // with this, you can force the browser to not make cache of the retrieved data
        dataType: "text",  // jQuery will infer this, but you can set explicitly
        success: function( data, textStatus, jqXHR ) {
            var resourceContent = data; // can be a global variable too...
            // process the content...
        }
    });
});
Xanarus
  • 763
  • 1
  • 6
  • 18
  • Unfortunately, this will fail in Google Chrome because it doesn't allow requests on local files. See [this thread](http://stackoverflow.com/questions/17947971/ajax-in-jquery-does-not-work-from-local-file) – blex May 18 '14 at 16:03
  • 1
    Actually, it is not going to work in any browser, for a local file. – blex May 18 '14 at 19:46
0

As You've mentionned HTML, I assume you want to do this in a browser; Well the only way to access a local file in a browser is by using the File API, and the file can only be obtained via a user's manipulation such selecting a file in an <input type='file'> element, or drag&dropping a file in your page.

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97
0

We could achieve this by, I should say, creating a virtual file!

Storing the contents of the text file into a Javascript string variable. However, one should consider all new lines and other special symbols\characters and etc.!

We than can markup a script tag in our HTML to load that *.js Javascript like this:

<script src="my_virtual_file.js"></script>

The only difference here is that a text file that could contain:

Goodnight moon
Follow the white rabbit

In a Javascript script string variable should look like this:

var my_virtual_file = "Goodnight moon\nFollow the white rabbit";

Later on, you can access this variable and treat it as you wish...

A programming language like Javascript that follows standards like ECMAScript, gives you a wide range of capabilities to treat and convert data from one type into another.

Once you have your Javascript script loaded, you can then access that variable by any button in your HTML by assigning a function call on its onclick attribute like this:

<button onclick="MyVirtualFile()"></button>

And ofcourse, you just add a script tag to your HTML, like this:

<script>
    functiion MyVirtualFile(){
        alert(my_virtual_file);
    };
</script>

... or your may just create and import another Javascript script containing that same function, under your desire.

If you are concerned about how much information you can store into a Javascript string variable, just take a look at this interesting (and old as this one :D) SO thread.

Lets see if this snippet works :):

var my_virtual_file = "Goodnight moon\nFollow the white rabbit"

function MyVirtualFile(){
    alert(my_virtual_file);
    // Do anything else with your virtual file
};
<!DOCTYPE html>
<html>

<head>
    <script src="my_virtual_file.js">
    </script>
</head>
<body>

  <h1>HTML Javascript virtual file</h1>
  <button onclick="MyVirtualFile()">Alert my_virtual_file</button>

</body>

</html>

You can programatically access and dynamically change the contents of your Javascript script, but you should remind that you need to reload your HTML so the browser can load the new contents.

On your filesystem, you can just treat this *.js as a *.txt file, and just change its contents keeping in mind the Javacript.

Logixor
  • 69
  • 1
  • 12