How to select file OR folder in file dialog

Dri*_*ngo 4 javascript file node.js electron

How would someone open up a file dialog in Node.js / electron to be able to select either a folder or a file.

When I use

<input type="file"/> 
Run Code Online (Sandbox Code Playgroud)

it will open up the file dialog but won't allow me to select a folder. But when I try

<input type="file" webkitdirectory/> 
Run Code Online (Sandbox Code Playgroud)

it will open up the dialog, but won't allow for folder selection.

What I want to do is just have one input button, or doesn't really have to be a button, but a way to launch the native system file explorer for both possibilities.

Alo*_*ler 5

您可以file system open dialogRenderer Process(浏览器窗口)启动A。

在您的上Main Process,您正在侦听Renderer Process,如果open-file-dialog从发送命令Renderer ProcessMain Process则会显示每个操作系统的“ 打开文件”对话框(如下所示,['openFile']正在发送属性,您也可以将其['openDirectory']用于“ 打开目录”对话框,或两者),并将所选文件\路径发送回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}`

});
Run Code Online (Sandbox Code Playgroud)

主要过程

//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)
  })
})
Run Code Online (Sandbox Code Playgroud)