2017-07-25 33 views
0

我想獲取文件位置作爲NW.JS中的變量。我從nw.js文檔中獲得了這段代碼,但無法弄清楚如何使用它來返回文件位置。我是否需要編寫一個腳本來使用id「fileDialog」來獲取結果? https://github.com/nwjs/nw.js/wiki/file-dialogs如何獲取文件位置作爲NWJS中的變量

**HTML** 
<input style="display:none;" id="fileDialog" type="file" /> 

**Javascript** 
<script> 
    function chooseFile(name) { 
    var chooser = document.querySelector(name); 
    chooser.addEventListener("change", function(evt) { 
     console.log(this.value); 
    }, false); 

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

回答

1

你最好通過文件列表input.files訪問文件名:

https://github.com/nwjs/nw.js/wiki/file-dialogs看一個的LILE列表部分。

被調用函數是一個異步回調,所以你不會能夠將名稱返回給調用函數。只處理回調中的所有文件。

function chooseFile(name, handleFile) { 
    var chooser = document.querySelector(name); 
    chooser.addEventListener("change", function(evt) { 
     for(var f of this.files){ 
      console.log(f.name); 
      console.log(f.path); 
      handleFile(f.name, f.path); 
     } 
    }, false); 

    chooser.click(); 
} 
chooseFile('#fileDialog', function(name, path){ ... /* do something with the file(s) */ }); 
+0

完美的作品!謝謝! – Marley

相關問題