javascript - 如何在文件对话框中选择文件或文件夹

标签 javascript node.js file electron

某人如何在 Node.js/electron 中打开文件对话框以便能够选择文件夹或文件。

当我使用

<input type="file"/> 

它将打开文件对话框,但不允许我选择文件夹。 但是当我尝试

<input type="file" webkitdirectory/> 

它将打开对话框,但不允许选择文件夹。

我想要做的只是有一个输入按钮,或者实际上不必是一个按钮,而是一种启动 native 系统文件资源管理器的方式,以实现这两种可能性。

最佳答案

您可以从渲染器进程(浏览器窗口)启动文件系统打开对话框

在您的Main Process 上,您正在监听Renderer Process,以防open-file-dialog 命令从Renderer ProcessMain 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/

相关文章:

node.js - Connect JS/Express JS url 处理程序的通用预处理程序?

c++ - 静态变量,单独编译

python - 如何在 block 文件中写入列表列表

javascript - 使用 ES6 模块而不是揭示模块模式的额外优势是什么?

javascript - 单击按钮时调用函数

javascript - 卡住对象的现有属性,但允许对象可扩展

node.js - socket.io 通过 XHR 轮询强制断开连接

javascript - 无法阻止表单以空输入提交

javascript - JQuery如何隐藏/显示具有唯一id的动态数量的div

perl - 如何在读取事件中捕获 File::Tail 异常