在JS中访问特定URL进行文件读取

问题描述 投票:0回答:1

我正在尝试用 JavaScript 读取文件。我正在使用 XAMPP 服务器,所有文件都在 htdocs 文件夹中。但是当我尝试从其他目录读取文件时它不起作用。

错误:

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
request.send(null);

JavaScript:

<!DOCTYPE html>
<html>
<body>
    <textarea id="box" rows="4" cols="50"> </textarea>

    
<script>

//get the contents of the text file START   
//Make sure in the JsonData.txt file, after each line there should not be any space ie when you click RIGHT arrow at the end of each line the cursor should go to next line beginning.

                
            function FileHelper()
            {}
            {
                FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
                {
                    var request = new XMLHttpRequest();
                    request.open("GET", pathOfFileToReadFrom, false);
                    request.send(null);
                    var returnValue = request.responseText;

                    return returnValue;
                }
            }

            var pathOfFileToRead = "file://d:/sampleData.txt";

            var contentsOfFileAsString = FileHelper.readStringFromFileAtPath
            (
                pathOfFileToRead
            );
            
            var contents_value = contentsOfFileAsString;
            alert(contents_value);
            document.getElementById("box").value = contents_value;
            
            //document.getElementById("demo").innerHTML = contents_value;       
            
            //get the contents of the text file STOP
</script>

</body>
</html>

在 JS 'pathOfFileToRead=filepath' 中,如果我将文件保存在同一个 htdocs 目录中,它工作正常,但如果我提供像我在上面的 JS 中给出的本地目录路径,则无法工作。

javascript file
1个回答
2
投票

您正在使用在浏览器中运行的 JavaScript。您不能使用 file:// 协议来读取文件,也不能使用驱动器号。

不过你仍然可以做你想做的事。您需要使用 url 引用您的文件并使用 http:// 调用它。 (你知道区别吗?!一个 url 有一个指向 Web 根目录的域名或 IP 地址,然后可能是端口号,然后是正斜杠分隔 Web 根目录下的每个文件夹。Windows 路径有一个驱动器号,然后是分隔的反斜杠每个文件夹。)

你的脚本中有很多小事情需要改进。我将从删除第 2 行上的一对空大括号开始。然后,我认为没有人在同步模式下使用 xmlhttp。您确实应该将异步与回调一起使用,并在开展业务之前检查是否成功(200)。

© www.soinside.com 2019 - 2024. All rights reserved.