[英]file content in textarea using Javascript
I want to display the content of a local file in a textarea-tag using javascript. 我想使用javascript在textarea标签中显示本地文件的内容。 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. 问题是我还不是Java专业人士。 i always get a reader.result is null error and i dont know why. 我总是得到一个reader.result为null错误,我不知道为什么。 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
. 当脚本运行此行时, FileReader
尚未完成工作,因此reader.result
很可能为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. 我建议从输入元素中删除multiple
,除非有必要,以避免不必要的复杂性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.