簡體   English   中英

nw.js:如何構建文件對話框以打開文件?

[英]nw.js: How do I build a file dialog to open a file?

我的應用程序使用占位符構建,單擊“加載”后可直接讀取文件。

<button id="loadbutton" type="button" class="btn btn-success" onclick="showTheFile()">Load</button></a>

showthefile()做一些事情,然后調用...

var keyMapLoc = '\\path\\to\\file.txt';
function readKeys(ffile) {
// read the keyfile
    var ffile = ffile || keyMapLoc;
    return fs.readFileSync(ffile, 'utf8');
}

這會將文件讀入解析后的應用程序,yotta yotta。

我遵循了這些說明並使用了演示。 打開應用后,文件對話框即會彈出,我得到了。

<html>
<body>
<input style="display:none;" id="fileDialog" type="file" />
<script>
  function chooseFile(name) {
    var chooser = document.querySelector(name);
    chooser.addEventListener("change", function(evt) {
      console.log(this.value);
    }, false);

    chooser.click();  
  }
  chooseFile('#fileDialog');
</script>
</body>
</html>

但是,即使我了解如何彈出文件對話框並且了解如何讀取/解析文件,但我還是很難將這個非常抽象的示例應用到現有的nwjs應用程序中。

根據我的應用程序的上述示例,我應該如何融入演示中,以便“加載”按鈕可以按預期的方式加載文件?

由於您未提供代碼,因此我將繼續進行演示。 您需要做的是觸發文件輸入元素的click事件,然后在發生change事件時,調用readKeys()

<!DOCTYPE html>
<html>
<body>
<input style="display:none;" id="fileDialog" type="file"/>

<button id="loadButton" type="button" class="btn btn-success"
        onclick="showTheFile()">Load</button>

<script>
    var fs = require('fs');
    var keyMapLoc = '\\path\\to\\file.txt';
    var chooser = document.querySelector("#fileDialog");

    // Set up the file chooser for the on change event
    chooser.addEventListener("change", function(evt) {
        // When we reach this point, it means the user has selected a file,
        // so invoke readKeys().
        // this.value contains the path to the selected file
        console.log(readKeys(this.value));
    }, false); 

    function showTheFile() {
        // Trigger click event on the chooser, this will bring up the
        // dialog
        chooser.click()
    }

    function readKeys(ffile) {
        var ffile = ffile || keyMapLoc;
        return fs.readFileSync(ffile, 'utf8');
    }
</script>
</body>
</html>

暫無
暫無

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

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