【问题标题】:How to show an open file native dialog with Electron?如何使用 Electron 显示打开的文件本机对话框?
【发布时间】:2018-02-01 14:27:57
【问题描述】:

我正在尝试向我的 Electron 应用程序添加功能,允许用户在应用程序中打开文件,特别是纯文本文件。查看 Electron 文档后,我找到了this 页面。我将此代码添加到我的app.js 文件中,并在我的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);
    });
  });
});

但是,当我运行此程序时,控制台中会显示此错误:Uncaught TypeError: dialog.showOpenDialog is not a function 我曾尝试使用远程,但无济于事。

有谁知道如何解决这个问题? 提前致谢

【问题讨论】:

    标签: javascript jquery menu electron


    【解决方案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
            }
        });
    });
    

    【讨论】:

    【解决方案2】:

    在你可以使用的主进程上

    const {dialog} = require('electron');
    
    dialog.showOpenDialog({properties: ['openFile'] }).then(function (response) {
        if (!response.canceled) {
            // handle fully qualified file name
          console.log(response.filePaths[0]);
        } else {
          console.log("no file selected");
        }
    });
    

    回复如下:

    {
     canceled: false,
     filePaths: [
        '<fullpath>/<filename>'
     ]
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 2010-11-08
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多