如何使用HTML 5 FileReader读取本地文件?

How to read local files using HTML 5 FileReader?

Objective

我正在制作一个应用程序,我需要使用 JavaScript 和 HTML 5 读取本地文件,没有任何 <input> 标签或任何用户交互。

我试过的

在我的研究中,我发现了两个在 SO 中被大量引用的教程:

但是,有一个问题。这两个教程都需要通过 input 标记进行用户交互,这是一个生命杀手,因为我想自动将文件内容读入字符串。

代码

到目前为止,我设法得到了以下代码:

let readFile = function(path) {
    let reader = new FileReader();

    reader.onload = function(e) {
        var text = reader.result;
        console.log(text);
    };

    // Read in the image file as a data URL.
    reader.readAsText(MissingFileHandle);
};

但是如您所见,我错过了重要的一步,我错过了 MissingFileHandle。我的想法是将 path 传递给此方法,这样该方法会在本地读取文件作为文本并将其打印到控制台中,但我无法实现这一点。

问题

给定相对路径,如何在不使用 <input> 标签的情况下使用 HTML 5 读取文件内容?

这个可以做个把戏。

HTML

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>

JS

window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

HTML5 fileReader 工具确实允许您处理本地文件,但这些必须由用户选择,您不能在用户磁盘上寻找文件。

Is it possible to load a file with JS/HTML5 FileReader on non served page?

How to open a local disk file with Javascript?

How to set a value to a file input in HTML?

Javascript read file without using input

这些链接可以帮助您找到答案。