如何通过NW.JS中的按钮单击来触发文件对话?
问题描述:
我想用一个图像作为按钮,在NW.JS中打开一个文件对话框,我该怎么做?如何通过NW.JS中的按钮单击来触发文件对话?
我有这个 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" />
这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) */ });
答
下面是完整的工作示例:
<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>
您可以使用“自定义文件输入”方法:https://*.com/questions/5813344/how-to-customize-input-type-file – yuriy636
这可能是有用的:https://www.npmjs。 com/package/nw-dialog。这就像文件对话的API。 – sandcastles