如何在文件对话框中select文件或文件夹
如何在Node.js / electron中打开文件对话框,以便能够select文件夹或文件。
当我使用
<input type="file"/>
它会打开文件对话框,但不会允许我select一个文件夹。 但是当我尝试
<input type="file" webkitdirectory/>
它会打开对话框,但不会允许select文件夹。
我想要做的只是一个inputbutton,或者不一定是一个button,而是一种启动本地系统文件浏览器的方法。
您可以从Renderer Process
(浏览器窗口)启动file system open dialog
。
在Main Process
,您正在监听Renderer Process
,如果从Renderer Process
发送了open-file-dialog
命令,则Main Process
将在每个操作系统中显示一个Open File对话框 (如下所示, ['openFile']
属性被发送,你也可以使用['openDirectory']
打开目录对话框,或两者),并将选定的文件\path发送到呈现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}` });
主stream程
//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) }) })
尝试添加directory
以及webkitdirectory
directory
。 否则请看这些:
在HTML页面的目录select器
如何从HTMLinputtypes“文件”或任何其他方式获取文件夹目录?
对于遇到类似问题的人来说,这只适用于电子。 但电子内置了一个时髦的文件对话框API,比原生HTML更灵活。
代码看起来像这样
const {dialog} = require('electron').remote; dialog.showOpenDialog({ properties: ["openDirectory","openFile"] },function (fileNames) { // do cool stuff here });