如何使用FileReader将文本文件加载到JavaScript中?
我试图将简单的文本文件加载到JavaScript中,不幸的是没有成功。 我的代码是:
var my_text:any;
var my_file:File = new File([], "C:\\Users\\riki7\\Downloads\\classes.txt");
var reader = new FileReader();
reader.onload = function() {
my_text = reader.result;
};
reader.readAsText(my_file);
alert(my_text);
在此代码运行后,我希望在弹出警报中看到class.txt文件内容,而是“未定义”。 我的文件包含a,b,c。
有人知道我的问题吗?也许是文件()构造函数的第一个参数?
I'm trying to load simple text file in javascript, unfortunately with no success.
my code is:
var my_text:any;
var my_file:File = new File([], "C:\\Users\\riki7\\Downloads\\classes.txt");
var reader = new FileReader();
reader.onload = function() {
my_text = reader.result;
};
reader.readAsText(my_file);
alert(my_text);
after this code runs, I would expect to see classes.txt file content in pop-up alert, instead I get 'undefined'.
my file contains a, b, c.
does anyone know what is my problem? maybe the first parameter for File() constructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须使用html tag
&lt; input type =“ file” id =“ input” /&gt; < /code>,然后将事件侦听器挂
上
在 我想就是这样。
您可以在那里找到更多示例:
如果您需要使用内容看到更改,请只需将警报移动到回调函数中:
因为
my_text
在外面调用警报时还没有准备好。You have to use html tag
<input type="file" id="input" />
and then hung a event listener on it, like thatthen after simply bypass your file into the FileReader
And i guess that would be it.
You can find more examples there: https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications
Having your code where your
alert
runs upfront the callback function. If you need to see alter with the content, simply move your alert into the callback function:because
my_text
is not ready when you call alert outside.