How to read local files using HTML 5 FileReader? [duplicate]

被刻印的时光 ゝ 提交于 2021-01-21 04:43:46

问题


Objective

I am making an application, and I need to read a local file using JavaScript and HTML 5, without any <input> tags or user interaction whatsoever.

What I tried

On my research, I found two tutorials that are heavily cited in SO:

  • https://www.html5rocks.com/en/tutorials/file/dndfiles/
  • http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

However, there is a problem. Both of this tutorials require user interaction via the input tag, which is a life killer since I want to read the contents of the file automatically into a string.

Code

So far I managed to get the following code:

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);
};

But as you can see, I am missing an important step, I am missing MissingFileHandle. My idea would be to pass a path to this method, and so the method would read the file locally as text and print it into the console, but I am unable to achieve this.

Question

Given a relative path, how can I read the contents of a file using HTML 5 without using <input> tags?


回答1:


The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.

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

These links help you to find answer.




回答2:


This Can do a trick.

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!"
            }
        });
}


来源:https://stackoverflow.com/questions/41849745/how-to-read-local-files-using-html-5-filereader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!