使用javascript点击按钮,阅读并显示文本文件内容 [英] Read and display the text file contents upon click of button using javascript

查看:1424
本文介绍了使用javascript点击按钮,阅读并显示文本文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击一个名为result的按钮,我想用java读取并显示一个文本文件(存在于我的本地驱动器位置中: C:\test.txt )脚本功能并在HTML文本区域中显示test.txt文件内容。

On click of a button called "result", I want to read and display a text file (which is present in my local drive location say: C:\test.txt) using java script function and display the test.txt file contents in a HTML text area.

我是java脚本的新手,有人可以建议读取和显示.txt文件内容的j​​ava脚本函数代码吗?

I am new to java script,can anyone suggest the code for java script function to read and display the contents of .txt file ?

感谢和问候
Deb

Thanks and regards Deb

推荐答案

对本地文件的Ajax请求将失败安全原因。

An Ajax request to a local file will fail for security reasons.

想象一个网站可以像您要​​求的那样访问计算机上的文件,但不会让您知道,并将内容发送给黑客。您不会想要这样,浏览器制造商负责保护您的安全!

Imagine a website that accesses a file on your computer like you ask, but without letting you know, and sends the content to a hacker. You would not want that, and browser makers took care of that to protect your security!

要读取硬盘驱动器上文件的内容,您需要有一个< input type =file> 让用户自己选择文件。您无需上传它。你可以这样做:

To read the content of a file located on your hard drive, you would need to have a <input type="file"> and let the user select the file himself. You don't need to upload it. You can do it this way :

<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var result = document.getElementById("result");

  reader.onload = function(event) {
    result.innerHTML = event.target.result;
  };

  reader.readAsText(selectedFile);
}

JS小提琴

这篇关于使用javascript点击按钮,阅读并显示文本文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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