使用 HTML5 和 JavaScript 导入纯文本文件
我是 JavaScript 新手,所以如果这个问题的答案是显而易见的,请原谅我。
我正在尝试为文本编辑器网络应用程序设置导入功能。
我的代码如下:
function dataImport() {
confirm("Are you sure you want to import the selected file? This will overwrite any data that is currently saved in the application workplace.");
var fileReader = new FileReader();
window.localStorage.setItem("AppData", fileReader.readAsText(document.querySelector("#import-selector").value));
};
它应该通过以下方式激活:
<input id="import-selector" type="file" /><button id="import-button" onclick="dataImport();">Import File</button>
然而,它不是将文件的内容写入本地存储,而是仅写入“未定义”一词。我认为发生了某种错误,但我不确定它是什么。
预先感谢您的任何帮助或建议。
I'm new to JavaScript, so forgive me if the answer to this question is an obvious one.
I'm trying to set up an import function for a text-editor web-application.
My code is as follows:
function dataImport() {
confirm("Are you sure you want to import the selected file? This will overwrite any data that is currently saved in the application workplace.");
var fileReader = new FileReader();
window.localStorage.setItem("AppData", fileReader.readAsText(document.querySelector("#import-selector").value));
};
And it should be activated by:
<input id="import-selector" type="file" /><button id="import-button" onclick="dataImport();">Import File</button>
Instead of writing the contents of the file to the localStorage, however, it merely writes the word 'undefined'. I take it some kind of error has happened, but I'm not sure what it is.
Thanks in advance for any help or advice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我从未听说过 HTML 中的
lick
事件。也许这是 HTML5 的新内容;)尝试将您的
onlick="...
触发器更改为onclick="...
也许这会起作用?
现在问题已解决,请尝试以下示例:Chrome FileReader
我尝试过,它工作完美。它将文件内容输出到错误控制台。
祝你好运!
I've never heard of a
lick
event in HTML. Maybe it's something new to HTML5 ;)Try changing your
onlick="...
trigger toonclick="...
Maybe that will work?
Now that that's fixed, try this example: Chrome FileReader
I tried it, and it works flawlessly. It outputs the file contents into the error console.
Good luck!