Load text from local .txt file into html textarea using JavaScript

江枫思渺然 提交于 2019-12-17 20:55:45

问题


I have a <textarea> element and a button that calls a loadFile() JavaScript function. I want this function to allow me to load the text from a .txt file on my local machine into the textarea. Any help with this would be greatly appreciated!


回答1:


You can use the File and FileReader objects to read local files.

You can use an input element with type="file" to allow the user to select a file.

<input id="myFile" type="file"/>
<textarea id="myTextArea" rows="4" columns="20"></textArea>

After the user has selected a file, you can get the File object from the input element. For example...

var file = document.getElementById("myFile").files[0];

You can then use a FileReader object to read the file into the text area. For example...

var reader = new FileReader();
reader.onload = function (e) {
    var textArea = document.getElementById("myTextArea");
    textArea.value = e.target.result;
};
reader.readAsText(file);



回答2:


I found a old topic about this: How do I load the contents of a text file into a javascript variable?

Have you read the last answer already? This works with a div instead of a textbox, but you could adapt the code a bit.

In the last piece of the last commenters post you could change this line:

document.getElementById("id01").innerHTML = out;

to:

document.getElementById("textbox01").innerHTML = out;

And in your HTML:

<textarea name="textbox01">Enter text here...</textarea>

Result:

function loadFile() {
    var xmlhttp = new XMLHttpRequest();
    var url = "file.txt";

    xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var myArr = JSON.parse(xmlhttp.responseText);
            myFunction(myArr);

            console.log("xmlhttp Request Asepted");
        }


    }

        xmlhttp.open("GET", url, true);
        xmlhttp.send();


        function myFunction(arr) {
            var out = "";
            var i;
            var row = 0;

        for(i = 0; i < arr.length; i++) {
           // console.log( arr[1].data); change data to what every you have in  your file
           // out +=  arr[i].data + '<br>' + arr[i].data2 ;
            document.getElementById("textbox01").innerHTML = out;

        }

    }
}


来源:https://stackoverflow.com/questions/33640325/load-text-from-local-txt-file-into-html-textarea-using-javascript

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