Read and display the text file contents upon click

2019-06-03 00:12发布

问题:

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 java script function and display the test.txt file contents in a HTML text area.

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

Thanks and regards Deb

回答1:

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



回答2:

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...
        }
    });
});


回答3:

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.