electron 如何使用电子获取文件夹路径

yhqotfr8  于 8个月前  发布在  Electron
关注(0)|答案(6)|浏览(275)

我对电子很陌生。谁能告诉我如何使用电子获取本地文件夹的相对路径?JavaScript没有这个功能。


的数据
我有一个选择文件按钮(见快照),所以我的问题是,当我选择一个文件夹,并点击打开按钮,那么它应该返回一个完整的目录路径。

khbbv19g

khbbv19g1#

正如@phuongle在评论中指出的那样,你想使用showOpenDialog()。类似这样:

var remote = require('remote');
var dialog = remote.require('electron').dialog;

var path = dialog.showOpenDialog({
    properties: ['openDirectory']
});

字符串
更新:如果以上方法不适用于您当前的Electron版本,您应该尝试更现代的导入:

const {dialog} = require('electron').remote;


此外,为了使用remote,您需要在主进程中创建窗口时设置enableRemoteModule

const myWindow = new BrowserWindow({
    webPreferences: {
        enableRemoteModule: true
    }
});

6qfn3psc

6qfn3psc2#

以下官方IPC tutorial为我工作

主进程:

import {dialog, ipcMain} from 'electron'
function createWindow () {
  mainWindow = new BrowserWindow({/*Your electron window boilerplate*/})
  ipcMain.handle('dialog:openDirectory', async () => {
    const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
      properties: ['openDirectory']
    })
    if (canceled) {
      return
    } else {
      return filePaths[0]
    }
  })
}

字符串

预加载脚本:

import {contextBridge, ipcRenderer} from 'electron'

contextBridge.exposeInMainWorld('myAPI', {
  selectFolder: () => ipcRenderer.invoke('dialog:openDirectory')
})

现在您可以从应用代码中调用selectFolder方法并获取用户输入。

window.myAPI.selectFolder().then(result=>{/* Do something with the folder path*/})

d6kp6zgx

d6kp6zgx3#

在Electron中,我们可以通过指定简单的输入元素type=“file”和webkitdirectory attribute '. <input id="myFile" type="file" webkitdirectory />来选择目录,我们可以通过File对象document.getElementById("myFile").files[0].path的path属性获得目录的完整路径

rks48beu

rks48beu4#

更新最新版本的electron(适用于25.3.0)和ES6 import

  • 第一件事:进口电子遥控器npm install --save @electron/remote
  • 然后在你的主进程中(你创建窗口的地方):
import * as remoteMain from '@electron/remote/main';
// ...
remoteMain.initialize();

function createWindow() {
  win = new BrowserWindow({
    webPreferences: {
      plugins: true,
      contextIsolation: false,
      webSecurity: false
      // ...
    }
  });

  remoteMain.enable(win.webContents);

  //...
}

字符串

  • 最后,我用来记录组件中文件路径的函数:
import * as remote from '@electron/remote';
// ...
async function getDir() {
  const showDialog = await remote.dialog.showOpenDialog({
    properties: ['openDirectory']
  });
  // Do things with showDialog
  console.log(showDialog.filePaths) // logs the directory path.
}

iyr7buue

iyr7buue5#

你可以使用Node的path.relative

wpx232ag

wpx232ag6#

对我来说,解决方案就是在react中使用all,在react组件中使用值true作为字符串。不需要额外的配置。
就像这样:

<input
    id="path-picker"
    type="file"
    webkitdirectory="true"
/>

字符串

编辑

事实证明,正如@cbartondock所提到的,它会递归地在目录中查找文件,这并不好!
我最终使用所需的电子遥控器的对话框。

相关问题