Read and display the text file contents upon click of button using javascript

*爱你&永不变心* 提交于 2020-01-03 03:02:24

问题


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.



来源:https://stackoverflow.com/questions/23723769/read-and-display-the-text-file-contents-upon-click-of-button-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!