如何使用Electron显示打开的文件本机对话框? [英] How to show an open file native dialog with Electron?
问题描述
我正在尝试为我的Electron应用添加功能,允许用户在应用中打开文件,特别是纯文本文件。在查看Electron文档后,我找到了这个页面。我将此代码添加到我的 app.js
文件中,该文件链接到我的 index.html
。
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);
});
});
});
但是,当我运行此命令时,此错误会显示在控制台中:未捕获TypeError:dialog.showOpenDialog不是函数
我尝试过使用远程,但无济于事。
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
推荐答案
const {dialog} = require('electron').remote;
document.querySelector('#selectBtn').addEventListener('click', function (event) {
dialog.showOpenDialog({
properties: ['openFile', 'multiSelections']
}, function (files) {
if (files !== undefined) {
// handle files
}
});
});
这篇关于如何使用Electron显示打开的文件本机对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!