javascript 如何使用 Electron 显示打开的文件本机对话框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45849190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show an open file native dialog with Electron?
提问by Inigo Mantoya
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 thispage. I added this code to my app.jsfile, which I linked to in my index.html.
我正在尝试向我的 Electron 应用程序添加功能,以允许用户在应用程序中打开文件,特别是纯文本文件。查看电子文档后,我找到了这个页面。我将此代码添加到我的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);
});
});
});
However, when I run this, this error shows up in the console: Uncaught TypeError: dialog.showOpenDialog is not a functionI have tried using remote, but to no avail.
但是,当我运行它时,控制台中会显示此错误:Uncaught TypeError: dialog.showOpenDialog is not a function我尝试使用远程,但无济于事。
Has anyone know how to fix this problem? Thanks in advance
有谁知道如何解决这个问题?提前致谢
回答by KBIIX
const {dialog} = require('electron').remote;
document.querySelector('#selectBtn').addEventListener('click', function (event) {
dialog.showOpenDialog({
properties: ['openFile', 'multiSelections']
}, function (files) {
if (files !== undefined) {
// handle files
}
});
});

