How can I trigger a file dialogue from a button click in NW.JS?

400 views Asked by At

I would like to use an image as button that opens a file dialogue in NW.JS, how can i do that?

I have this HTML

<button id="open" style="background: none;"><img src="images/open.png" style="width:20px;background:none;"></button></div>
<input style="display:none;" id="fileDialog" type="file" />

And this JS

function chooseFile(name, handleFile) {
    const chooser = document.querySelector(name);
    chooser.onchange = function () {
        for (const f of this.files) {
            console.log(f.name);
            console.log(f.path);
            handleFile(f.name, f.path);
        }
    };
    chooser.click();
}
chooseFile('#fileDialog', function(name, path){ ... /* do something with the file(s) */ });
1

There are 1 answers

0
dimacpp On

Here is complete working example:

<script>
openbtn.addEventListener('click', e => opendlg.click());

opendlg.addEventListener('change', e => {
    let files = e.target.value;
    if (files) {
        e.target.value = ''; // or you will not receive change-event next time on the same files
        files.split(';').forEach(filepath => {
            alert(filepath);
        });
    }

});
</script>