簡體   English   中英

您如何在PC上讀取本地文件並使用javascript不斷對其進行更新?

[英]How do you read a local file on your PC and update it constantly in javascript?

因此,我制作了一個java程序,該程序運行IPs列表,對其進行ping操作,並更新設備狀態文件。 我想知道如何將文件打開到webpage並進行更新,因此用戶可以打開網頁並僅查看文件中的數據列表,而不必選擇文件或刷新頁面。

使用javascript/html可行嗎?

到目前為止,這是我正在使用的代碼:

    <html>
    <head>
    <title>Import Data</title>
    <script>

        var openFile = function() {
            var input = event.target;

            var reader = new FileReader();
            reader.onload = function() {
                var text = reader.result;
                var node = document.getElementById('output');
                node.innerText = text;
                console.log(reader.result.substring(0,200));
            };

            reader.readAsText(input.files[0]);
            setTimeout(openFile(),1000);
        };
    </script>
    </head>
    <body>
    <input type='file' accept='text/plain' onchange='openFile()'><br>
    <div id='output'>
    </body>
    </html>

但是我似乎無法找到將文件的路徑硬編碼到哪里。當我使用這種手動選擇方法時,無論文件的元素增加還是減少,它都會更新一次。

編輯:

我將其范圍縮小到需要上傳文件的位置:

    <html>
       <head>
       <title></title>
       <script>
       function uploadFile() {
           var reader = new FileReader();
           reader.onload = function(event) {
              var contents = event.target.result;
              console.log("File contents: " + contents);
           };

           reader.onerror = function(event) {
              console.error("File could not be read! Code: " + event.target.error.code);
           };

           var fileInputElement = document.getElementById("FileName");
           reader.readAsText(fileInputElement.files[0]);
           console.log(fileInputElement.files[0]);
        }
        </script>
        </head>
        <body>
        <input type='file' accept='text/plain' value='RESULTS.txt' id='FileName' onchange='uploadFile()' style="display:none;">
        </body>
     </html>

如果我嘗試僅在字符串中鍵入文件路徑,則會抱怨不是鍵入“ blob”。 當我這樣做時,它要求用戶輸入文件名,但顯然看不到。 我如何才能使“文件”變量成為靜態變量,以便它始終在不提示用戶的情況下打開該文件?

做更多的研究,這是為什么您不能從本地計算機訪問文件的安全原因。

因此,代替所有這些,我編寫了一些代碼,這些代碼將不斷加載所選文件,以便您可以隨時查看更改的內容:

<html>
<head>
<title>Import Data</title>
<script>
var input;

    var openFile = function() {

        var reader = new FileReader(event);
        reader.onload = function() {
            var text = reader.result;
            var node = document.getElementById('output');
            node.innerText = text;
            console.log(reader.result.substring(0,200));
        };

        reader.readAsText(input.files[0]);
        setTimeout(openFile,1000);
    };
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='input = event.target; openFile(event);'><br>
<div id='output'>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM