某人如何在 Node.js/electron 中打开文件对话框以便能够选择文件夹或文件。
当我使用
<input type="file"/>
它将打开文件对话框,但不允许我选择文件夹。 但是当我尝试
<input type="file" webkitdirectory/>
它将打开对话框,但不允许选择文件夹。
我想要做的只是有一个输入按钮,或者实际上不必是一个按钮,而是一种启动 native 系统文件资源管理器的方式,以实现这两种可能性。
最佳答案
您可以从渲染器进程
(浏览器窗口)启动文件系统打开对话框
。
在您的Main Process
上,您正在监听Renderer Process
,以防open-file-dialog
命令从Renderer Process
,Main Process
将根据操作系统显示打开文件对话框(如下所示,['openFile' ]
属性被发送,您也可以将 ['openDirectory']
用于Open Directory 对话框,或同时使用它们)并将发送回选定的Renderer Process
的文件\路径。
渲染器进程
//Adding an event listener to an html button which will send open-file-dialog to the main process
const ipc = require('electron').ipcRenderer
const selectDirBtn = document.getElementById('select-file')
selectDirBtn.addEventListener('click', function (event) {
ipc.send('open-file-dialog')
});
//Getting back the information after selecting the file
ipc.on('selected-file', function (event, path) {
//do what you want with the path/file selected, for example:
document.getElementById('selected-file').innerHTML = `You selected: ${path}`
});
主进程
//listen to an open-file-dialog command and sending back selected information
const ipc = require('electron').ipcMain
const dialog = require('electron').dialog
ipc.on('open-file-dialog', function (event) {
dialog.showOpenDialog({
properties: ['openFile']
}, function (files) {
if (files) event.sender.send('selected-file', files)
})
})
关于javascript - 如何在文件对话框中选择文件或文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44773029/