如何在Node.js/electron中打開文件對話框以便能夠選擇文件夾或文件。如何在文件對話框中選擇文件或文件夾
當我使用
<input type="file"/>
它會打開文件對話框,但不會讓我選擇一個文件夾。 但當我嘗試
<input type="file" webkitdirectory/>
它將打開的對話框中,但不會允許文件夾選擇。
我想要做的只是一個輸入按鈕,或者不一定是一個按鈕,而是一種啓動本地系統文件資源管理器的方法。
如何在Node.js/electron中打開文件對話框以便能夠選擇文件夾或文件。如何在文件對話框中選擇文件或文件夾
當我使用
<input type="file"/>
它會打開文件對話框,但不會讓我選擇一個文件夾。 但當我嘗試
<input type="file" webkitdirectory/>
它將打開的對話框中,但不會允許文件夾選擇。
我想要做的只是一個輸入按鈕,或者不一定是一個按鈕,而是一種啓動本地系統文件資源管理器的方法。
您可以啓動從Renderer Process
一個file system open dialog
(瀏覽器窗口)。
在您Main Process
,您正在收聽的Renderer Process
,在open-file-dialog
命令從Renderer Process
發的情況下,Main 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}`
});
主要工藝流程
//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 Chooser in HTML page
How to get folder directory from HTML input type "file" or any other way?
對於運行到類似的麻煩任何人,電子這僅適用。但電子內置了一個時髦的文件對話框API,它比原生HTML對象更靈活。
的代碼看起來是這樣的
const {dialog} = require('electron').remote;
dialog.showOpenDialog({
properties: ["openDirectory","openFile"]
},function (fileNames) {
// do cool stuff here
});
您可能意味着'但不會允許文件selection.' – mplungjan
https://github.com/electron/電子/斑點/主/ docs/api/dialog.md#dialogshowcertificatetrustdialogbrowserwindow選項回調 - 馬科斯-windows說,這是不可能的Windows和Linux(這不意味着它可能爲OSX?)但它soun無論如何,這是一個更好的方式來打開電子對話框。 – Kaiido