简体   繁体   English

如何阅读本地文本文件?

[英]How do I read a local text file?

I want to read a local text file automatically whenever my webpage is opened on my computer. 我想在计算机上打开网页时自动读取本地文本文件。 How can I do this? 我怎样才能做到这一点? I used the following code from one of solutions answered on this site and it says "Access is denied". 我使用了从该网站上回答的一种解决方案中获得的以下代码,并显示“访问被拒绝”。

<script type="text/javascript">
var fileDisplayArea = document.getElementById('fileText');  //to show output
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///Location/fileToBeRead.txt");
</script>  

Is there any other solution to this problem? 还有其他解决方案吗?

You cannot read file off a persons local machine. 您无法从人员本地计算机上读取文件。

You can only read files from the same domain that your site is running on (or if using jsonp to get past XSS rules) 您只能从运行您的网站的同一域中读取文件(或者如果使用jsonp获取过去的XSS规则)

You should not be reading files on a client machine. 您不应该在客户端计算机上读取文件。 Its a security issue and hence not allowed (access denied). 这是一个安全问题,因此是不允许的(访问被拒绝)。 If you want to store data on client machine use cookies rather or as correctly pointed out use a html session or local storage. 如果要在客户端计算机上存储数据,请使用Cookie或正确指出使用HTML会话或本地存储。

为了安全起见,天生就没有方法(从URL ... file:///... )读取系统文件。

您可能可以使用HTML5的本地存储功能来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM