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', '下载失败', '当前模型提交终端,请排查问题后重试。');
    }
  });
相关推荐
rzl0213 分钟前
java web5(黑马)
java·开发语言·前端
Amy.Wang14 分钟前
前端如何实现电子签名
前端·javascript·html5
海天胜景16 分钟前
vue3 el-table 行筛选 设置为单选
javascript·vue.js·elementui
今天又在摸鱼17 分钟前
Vue3-组件化-Vue核心思想之一
前端·javascript·vue.js
蓝婷儿18 分钟前
每天一个前端小知识 Day 21 - 浏览器兼容性与 Polyfill 策略
前端
百锦再21 分钟前
Vue中对象赋值问题:对象引用被保留,仅部分属性被覆盖
前端·javascript·vue.js·vue·web·reactive·ref
jingling55525 分钟前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架
拾光拾趣录30 分钟前
CSS 深入解析:提升网页样式技巧与常见问题解决方案
前端·css
莫空000031 分钟前
深入理解JavaScript属性描述符:从数据属性到存取器属性
前端·面试
guojl32 分钟前
深度剖析Kafka读写机制
前端