【问题标题】:Electron - Open file from menuElectron - 从菜单打开文件
【发布时间】:2017-02-17 21:21:21
【问题描述】:

我的电子应用程序中有一个按钮,上面写着“打开文件”,当你点击它时,打开文件对话框会出现,我可以选择一个文件。

但是,当我从应用程序工具栏中单击菜单项时,如何打开“打开文件对话框”?

这是我在工具栏菜单子菜单中的标签:

label: 'Open',
accelerator: 'CmdOrCtrl+O'

我想做这样的事情:

label: 'Open',
accelerator: 'CmdOrCtrl+O',
role: 'open'

但没有“开放”这样的角色。

如何实现打开打开文件对话框的点击事件?

Main.js 打开文件部分:

const ipc = require('electron').ipcMain
const dialog = require('electron').dialog

ipc.on('open-file-dialog', function (event) {
  dialog.showOpenDialog({
    properties: ['openFile', 'openDirectory']
  }, function (files) {
    if (files) event.sender.send('selected-file', files)
  })
})

index.js:

const ipc = require('electron').ipcRenderer
const selectDirBtn = document.getElementById('open')

selectDirBtn.addEventListener('click', function (event) {
    ipc.send('open-file-dialog')
})

ipc.on('selected-file', function (event, path) {
    document.getElementById('selected-file').innerHTML = `► ${path}`
    document.getElementById('selected-file2').innerHTML = `${path}`
})

【问题讨论】:

    标签: javascript node.js electron


    【解决方案1】:

    Prime:使用 IPC 在主进程和渲染进程之间进行通信

    这是一个例子:

    // main.js 
    
    const { app, BrowserWindow, Menu, dialog, ipcMain } = require('electron')
    // wait until the app is ready before you can do anything 
    app.whenReady().then(function() {
      // setting up the main window object 
    
      const mainWindow = new BrowserWindow({
        backgroundColor: '#FFF',
        webPreferences: {
          // devTools: true,
          nodeIntegration: true
        },
        show: false,
      })
    
      // setting up the menu with just two items 
      const menu = Menu.buildFromTemplate([
        {
          label: 'Menu',
          submenu: [
            {
               label:'Open File',
               accelerator: 'CmdOrCtrl+O',
               // this is the main bit hijack the click event 
               click() {
                  // construct the select file dialog 
                  dialog.showOpenDialog({
                    properties: ['openFile']
                  })
                  .then(function(fileObj) {
                     // the fileObj has two props 
                     if (!fileObj.canceled) {
                       mainWindow.webContents.send('FILE_OPEN', fileObj.filePaths)
                     }
                  })
      // should always handle the error yourself, later Electron release might crash if you don't 
                  .catch(function(err) {
                     console.error(err)  
                  })
               } 
           },
           {
               label:'Exit',
               click() {
                  app.quit()
               } 
             }
          ]
        }
      ])
      Menu.setApplicationMenu(menu)
      // now run it 
      mainWindow.loadURL(`file://${__dirname}/index.html`)
      mainWindow.show()
    })
    
    

    不会显示index.html,您应该知道该怎么做,只需将render.js 包含到HTML 文档中即可。

    现在是 render.js

    // render.js 
    const { ipcRenderer } = window.require('electron')
    ipcRenderer.on('FILE_OPEN', (event, args) => {
      // here the args will be the fileObj.filePaths array 
      // do whatever you need to do with it 
      console.log('got FILE_OPEN', event, args)
    })
    
    

    这是在 Electron 9.X 上测试过的

    【讨论】:

      【解决方案2】:

      我有两个按钮,一个不可见的输入文件和可见的样式按钮。

      <input type="file" id="fileId" style="display:none;" />
      <button class="btn-lg btn-primary center-block" type="button"
          id="btnLoadFile">Load File</button>
      

      在js中,我设置了带样式的按钮点击事件,触发输入文件点击事件。

      document.getElementById('btnLoadFile').addEventListener("click", function(){
          document.getElementById('fileId').click();
      });
      

      然后我有一个输入文件元素的 on change 事件侦听器,它对文件执行一些操作。

      document.getElementById('fileId').addEventListener('change', function(e){
          //use the file here
          var files = e.target.files;
          var f = files[0]; {
              var reader = new FileReader();
              var name = f.name;
              reader.onload = function (e) {
                  console.log(e.target.result);
              };
              reader.readAsBinaryString(f);
          }
      });
      

      希望这会有所帮助。

      【讨论】:

      • 我不认为这解决了 OP 关于使菜单栏的 open 功能正常工作的问题。
      猜你喜欢
      • 2015-08-25
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      • 2015-08-03
      • 1970-01-01
      • 2018-02-12
      相关资源
      最近更新 更多