electron下载文件,弹窗选择下载路径,并通知下载进度

1:在window.js中 引入session

复制代码
import { app, BrowserWindow, ipcMain, dialog, shell, session } from 'electron';

2:发送下载请求

复制代码
 // 在主进程监听渲染进程发送的 'start-download' 事件
    ipcMain.on('start-download', async (event, downloadUrl) => {
      let win = BrowserWindow.getAllWindows()[0];
    });

3:弹窗选择路径

复制代码
 // 在主进程监听渲染进程发送的 'start-download' 事件
    ipcMain.on('start-download', async (event, downloadUrl) => {
      let win = BrowserWindow.getAllWindows()[0];
         const savePath = await dialog.showSaveDialog(win[0], {
        defaultPath: path.basename(downloadUrl), // 使用源文件名作为默认保存文件名
      });
      console.log(savePath.canceled, savePath.filePath);
    });

4:判断下载地址,如果存在就下载,并监听发送进度

复制代码
 ipcMain.on('start-download', async (event, downloadUrl) => {
      let win = this.getAllWindows();
      const savePath = await dialog.showSaveDialog(win[0], {
        defaultPath: path.basename(downloadUrl), // 使用源文件名作为默认保存文件名
      });
      console.log(savePath.canceled, savePath.filePath);
      if (!savePath.canceled) {
        const ses = session.fromPartition('persist:my-session');
        // 先移除之前可能已经注册的监听器
        ses.removeAllListeners('will-download');
        ses.on('will-download', (event, item, webContents) => {
          let win = BrowserWindow.getAllWindows()[0];
          const fileName = item.getFilename();
          console.log(`开始下载: ${fileName}`);
          // const savePath = path.join('C:', 'Users', 'A', 'Downloads', fileName);
          item.setSavePath(savePath.filePath);

          win.webContents.send('download-started', { fileName });

          item.on('updated', (event, state) => {
            if (state === 'interrupted') {
              console.log('下载中断...');
            } else if (state === 'progressing') {
              if (item.isPaused()) {
                console.log('下载暂停...');
              } else {
                console.log(
                  savePath.filePath,
                  `下载进度: ${((item.getReceivedBytes() / item.getTotalBytes()) * 100).toFixed(
                    2,
                  )}%`,
                );
              }
            }
          });

          item.on('done', (event, state) => {
            if (state === 'completed') {
              console.log('文件下载完成!');
              win.webContents.send('download-success', fileName);
            } else {
              console.log('下载失败');
            }
          });
        });

        // 开始下载文件
        const downloadItem = ses.downloadURL(downloadUrl);
      }
    });

5:在preload.js中暴露下载以及通知操作

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

contextBridge.exposeInMainWorld('electronAPI', {
  downloadSuccess: (callback) =>
  ipcRenderer.on('download-success', (e, savePath) => callback(savePath)),
  downloadFailed: () => ipcRenderer.on('download-failed', (e) => callback(e)),
  onDownloadStarted: (url) => ipcRenderer.send('start-download', url),
});

6:在渲染进程中使用

复制代码
//下载项目
  const downloadProject = () => {
    // const fileUrl = 'http://192.168.1.999:8/server/core.jar'; // 替换为实际的文件 URL
    // window.electronAPI.onDownloadStarted(fileUrl);
  };
  window.electronAPI.downloadSuccess((res) => {
    if (res) {
    console.log('success', '下载成功', `${res}下载成功,可在客户端首页打开。`);
    }
  });
  window.electronAPI.downloadFailed((res) => {
    if (res) {
      console.log('error', '下载失败', '当前模型提交终端,请排查问题后重试。');
    }
  });
相关推荐
qczg_wxg3 小时前
React Native的动画系统
javascript·react native·react.js
漂流瓶jz5 小时前
解锁Babel核心功能:从转义语法到插件开发
前端·javascript·typescript
周小码5 小时前
shadcn-table:构建高性能服务端表格的终极解决方案 | 2025最新实践
前端·react.js
大怪v5 小时前
老乡,别走!Javascript隐藏功能你知道吗?
前端·javascript·代码规范
ERP老兵-冷溪虎山5 小时前
Python/JS/Go/Java同步学习(第三篇)四语言“切片“对照表: 财务“小南“纸切片术切凭证到崩溃(附源码/截图/参数表/避坑指南/老板沉默术)
java·javascript·python·golang·中医编程·四语言同步学习·职场生存指南
webYin6 小时前
vue2 打包生成的js文件过大优化
前端·vue.js·webpack
gnip6 小时前
结合Worker通知应用更新
前端·javascript
叶玳言6 小时前
【LVGL】从HTML到LVGL:嵌入式UI的设计迁移与落地实践
前端·ui·html·移植
高级测试工程师欧阳6 小时前
HTML 基本结构
前端
Gazer_S6 小时前
【Element Plus 表单组件样式统一 & CSS 文字特效实现指南】
前端·css·vue.js