简体   繁体   中英

file content in textarea using Javascript

I want to display the content of a local file in a textarea-tag using javascript. To do so, i found the following workaround:

<textarea id="queryContent"></textarea>
    <input type="file" multiple id="queryInput">
    <script>
        var input = document.getElementById("queryInput");
        input.addEventListener("change", function () {
            Array.prototype.forEach.call(input.files, function (file) {
                var reader = new FileReader();
                reader.addEventListener("load", function () {
                    console.log("File", file.name, "starts with",
                        reader.result.slice(0,20));
                });
                reader.readAsText(file);
                document.getElementById("queryContent").innerText = reader.result.toString();
            });
        });
    </script> 

The problem is i am not a pro in Javascript yet. i always get a reader.result is null error and i dont know why. I appreciate your help!

This line:

document.getElementById("queryContent").innerText = reader.result.toString();

should happen inside the callback. When the script runs this line, the FileReader has not finished his job yet and therefore reader.result is very likely to be null .

Please try this code:

var input = document.getElementById("queryInput");
input.addEventListener("change", function () {
    Array.prototype.forEach.call(input.files, function (file) {
        var reader = new FileReader();
        reader.addEventListener("load", function () {
            console.log("File", file.name, "starts with", reader.result.slice(0,20));
            document.getElementById("queryContent").innerText = reader.result.toString();
        });
        reader.readAsText(file);
    });
});

PS

I would recommend to remove the multiple from the input element, unless it is required, to avoid unnecessary complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM