乐闻世界logo
搜索文章和话题

How to show an open file native dialog with Electron?

1个答案

1

In Electron, opening the local file chooser dialog is typically achieved by using the dialog module. The dialog module is part of Electron and provides methods to invoke native system dialogs, such as opening files, saving files, and displaying message prompts. To open the file chooser dialog, we can use the dialog.showOpenDialog() method.

Here is an example of how to use the dialog.showOpenDialog() method to open the file chooser dialog in an Electron application:

First, ensure that you have set up the Electron environment and can run a basic Electron application.

Then, in your Electron application's main process file (typically main.js or index.js), you can add the following code to implement the file chooser dialog functionality:

javascript
const { app, BrowserWindow, dialog } = require('electron'); app.on('ready', () => { let mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); mainWindow.loadFile('index.html'); // Load a web page // Open the file chooser dialog dialog.showOpenDialog(mainWindow, { properties: ['openFile', 'multiSelections'] // Enable multi-selection }).then(result => { console.log(result.canceled); console.log(result.filePaths); }).catch(err => { console.error(err); }); }); app.on('window-all-closed', () => { app.quit(); });

In this code, when the Electron application is ready, we create a new browser window and load an HTML file. Then, we use the dialog.showOpenDialog() method to open the file chooser dialog. We set the properties option to enable multi-selection (multiSelections) and file selection (openFile).

After the dialog.showOpenDialog() Promise resolves, we can retrieve the user-selected file paths and cancellation status via the result object. If the user cancels the dialog, result.canceled will be true; otherwise, you can obtain the user-selected file paths from the result.filePaths array.

This feature is highly valuable in real-world applications, especially when retrieving files from the user's local system. For instance, if you are developing an image editing application, users may need to select image files from their computer for editing.

2024年6月29日 12:07 回复

你的答案