使用JavaScript将文本从本地.txt文件加载到html textarea [英] Load text from local .txt file into html textarea using JavaScript

查看:171
本文介绍了使用JavaScript将文本从本地.txt文件加载到html textarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< textarea> 元素和一个调用 loadFile() JavaScript函数的按钮。我希望这个函数允许我将本地机器上的.txt文件中的文本加载到textarea中。任何帮助都将非常感谢!

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!

推荐答案

您可以使用File和FileReader对象来读取本地文件。

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

您可以使用type =file的输入元素来允许用户选择文件。

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>

用户选择文件后,您可以从input元素中获取File对象。例如......

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];

然后,您可以使用FileReader对象将文件读入文本区域。例如......

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

这篇关于使用JavaScript将文本从本地.txt文件加载到html textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆