第7章:Electron文件系统操作(2)

7.2 文件对话框

Electron 提供了 dialog 模块用于显示文件打开和保存对话框。

7.2.1 显示文件打开对话框

主进程代码:

javascript 复制代码
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');

let mainWindow;

const createMainWindow = () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    }
  });

  mainWindow.loadFile('index.html');
  mainWindow.webContents.openDevTools();
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
};

app.on('ready', createMainWindow);
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
app.on('activate', () => {
  if (mainWindow === null) {
    createMainWindow();
  }
});

// 处理文件打开对话框请求
ipcMain.handle('open-file-dialog', async () => {
  const result = await dialog.showOpenDialog({
    properties: ['openFile']
  });
  if (result.canceled) {
    return { success: false };
  } else {
    return { success: true, filePaths: result.filePaths };
  }
});

预加载脚本(preload.js):

javascript 复制代码
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  openFileDialog: () => ipcRenderer.invoke('open-file-dialog')
});

渲染进程代码:

html 复制代码
<!DOCTYPE html>
<html>
<head>
  <title>File Dialog Example</title>
</head>
<body>
  <h1>Open File Dialog Example</h1>
  <button id="openFileDialog">Open File</button>
  <p id="filePath"></p>

  <script>
    document.getElementById('openFileDialog').addEventListener('click', async () => {
      const result = await window.electronAPI.openFileDialog();
      if (result.success) {
        document.getElementById('filePath').innerText = 'Selected file: ' + result.filePaths[0];
      } else {
        document.getElementById('filePath').innerText = 'No file selected';
      }
    });
  </script>
</body>
</html>

7.2.2 显示文件保存对话框

主进程代码:

javascript 复制代码
const { app, BrowserWindow, dialog } = require("electron");
const { ipcMain } = require("electron");

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: true,
      preload: __dirname + "/preload.js",
    },
  });

  mainWindow.loadFile("index.html");
}

app.whenReady().then(() => {
  createWindow();

  app.on("activate", function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });

  // 添加ipcMain.handle处理来自渲染进程的save-file请求
  ipcMain.handle("save-file", async (event, options) => {
    try {
      const result = await dialog.showSaveDialog(mainWindow, options);
      return result.filePath; // 直接返回文件路径给renderer,无需额外的reply
    } catch (err) {
      console.error("Error showing save dialog:", err);
      throw err;
    }
  });
});

app.on("window-all-closed", function () {
  if (process.platform !== "darwin") app.quit();
});

预加载脚本(preload.js):

javascript 复制代码
const { contextBridge, ipcRenderer } = require("electron");

// 在preload中暴露安全的API给渲染进程
contextBridge.exposeInMainWorld("api", {
  saveFile: (options) => {
    return ipcRenderer.invoke("save-file", options);
  },
});

渲染进程代码:

javascript 复制代码
document.getElementById("saveButton").addEventListener("click", async () => {
  const options = {
    title: "Save your File",
    defaultPath: "untitled.txt",
    filters: [
      { name: "Text Files", extensions: ["txt"] },
      { name: "All Files", extensions: ["*"] },
    ],
  };

  try {
    const filePath = await window.api.saveFile(options);
    if (filePath) {
      console.log(`File will be saved at: ${filePath}`);
      // 这里可以添加保存文件的具体逻辑
    } else {
      console.log("User canceled the save operation.");
    }
  } catch (error) {
    console.error("Error during file save operation:", error);
  }
});

HTML代码:

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Save File Example</title>
  </head>
  <body>
    <h1>Click to Save a File</h1>
    <button id="saveButton">Save File</button>

    <script src="./renderer.js"></script>
  </body>
</html>
相关推荐
liangshanbo12152 小时前
JavaScript 面试题:Object.keys() 的返回顺序是无序的吗?
开发语言·javascript·ecmascript
geovindu2 小时前
css: Timeline scribble
前端·css·iphone
沙漠之主10 小时前
C++编程教学设计资料:从入门到实战的完整课程方案
java·前端·c++
hasty10 小时前
不上传新包,也能改变用户拿到的版本:npm dist-tag 的 OIDC 权限治理
前端·npm·node.js
Csvn11 小时前
diff 算法(虚拟 DOM Reconciliation)
前端
前端snow12 小时前
ai agent --- 文件存储
前端
Frag0ut12 小时前
Chrome四大版本获取及共存指南:Stable/Beta/Dev/Canary
前端·chrome·浏览器·dev·beta·canary·共存版
IT_陈寒13 小时前
SpringBoot自动配置坑了我一把,原来是这样绕过去的
前端·人工智能·后端
广州华水科技13 小时前
单北斗GNSS变形监测在大坝安全监测中的应用与优势
前端
zeng不错14 小时前
B站 173 个投稿活动看到眼瞎?我写了个扩展,主打一个精准打击
前端