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

How to allow users to pick a file path in electron

1个答案

1

In Electron, allowing users to select local files is typically done using the showOpenDialog or showOpenDialogSync methods from the dialog module. These methods open a local file selection dialog, enabling users to choose files or directories. The main difference is that showOpenDialog is asynchronous, while showOpenDialogSync is synchronous. It is generally recommended to use the asynchronous method to avoid blocking the main thread.

Below, I will provide a specific example demonstrating how to implement this functionality in Electron.

Step 1: Import the required modules

In your Electron application's main process file, you first need to import the dialog module, which is imported from the electron package.

javascript
const { app, BrowserWindow, dialog } = require('electron'); let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); mainWindow.loadFile('index.html'); mainWindow.on('closed', function () { mainWindow = null; }); } app.on('ready', createWindow);

Step 2: Implement the file selection functionality

You can create a function to handle the file selection logic, which is triggered when a user initiates an event (such as clicking a button).

javascript
function selectFile() { dialog.showOpenDialog(mainWindow, { properties: ['openFile', 'multiSelections'], filters: [ { name: 'Images', extensions: ['jpg', 'png', 'gif'] }, { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] }, { name: 'Documents', extensions: ['doc', 'pdf', 'txt'] } ] }).then(result => { if (!result.canceled) { console.log(result.filePaths); // Process the selected files here } }).catch(err => { console.log(err); }); }

In the above code snippet, the showOpenDialog method is configured with an object where properties specifies the selectable types (e.g., files, multi-selection), and filters restricts the file types users can choose.

Step 3: Trigger selection from the renderer process

In your renderer process page (e.g., index.html), add a button to initiate file selection.

html
<button onclick="selectFile()">Select File</button> <script> function selectFile() { window.electronAPI.selectFile(); } </script>

Then, in your preload script or main process, expose the selectFile method to the renderer process.

javascript
const { contextBridge } = require('electron'); contextBridge.exposeInMainWorld('electronAPI', { selectFile: selectFile });

This approach ensures that clicking the button triggers the file selection logic defined in the main process via the exposed API.

2024年6月29日 12:07 回复

你的答案