How to show an open file native dialog with Electron?

陌路散爱 提交于 2019-12-22 04:36:47

问题


I am trying to add functionality to my Electron app that will allow users to open a file in the app, specifically plain text files. After looking at the Electron documentation, I found this page. I added this code to my app.js file, which I linked to in my index.html.

var fs = require('fs');
var dialog = require('electron');
$openFile = $('#openBtn');
$editor = $('#editor');

$openFile.click(function(){
  dialog.showOpenDialog(function(fileNames) {
    if (fileNames === undefined) return;
    var fileName = fileNames[0];

    fs.readFile(fileName, 'utf-8', function (err, data) {
      $editor.val(data);
    });
  });
});

However, when I run this, this error shows up in the console: Uncaught TypeError: dialog.showOpenDialog is not a function I have tried using remote, but to no avail.

Has anyone know how to fix this problem? Thanks in advance


回答1:


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

document.querySelector('#selectBtn').addEventListener('click', function (event) {
    dialog.showOpenDialog({
        properties: ['openFile', 'multiSelections']
    }, function (files) {
        if (files !== undefined) {
            // handle files
        }
    });
});


来源:https://stackoverflow.com/questions/45849190/how-to-show-an-open-file-native-dialog-with-electron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!