电子 - 从菜单打开文件

时间:2016-10-09 08:33:18

标签: javascript node.js electron

我的电子应用中有一个按钮,表示打开文件',当您点击它时会出现打开文件对话框,我可以选择一个文件。

虽然,我怎样才能打开“打开文件”对话框'单击应用程序工具栏中的菜单项时框?

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

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

我想做类似的事情:

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

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

如何实现打开打开文件对话框的on click事件?

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}`
})

2 个答案:

答案 0 :(得分: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);
    }
});

希望这有帮助。

答案 1 :(得分:0)

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到HTML文档中就不会显示render.js,您应该知道该怎么做。

现在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上运行