当前位置: 首页 > news >正文

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', '下载失败', '当前模型提交终端,请排查问题后重试。');
    }
  });

7:文件流下载

 ipcMain.on('start-download', async (event, downloadUrl, fileName, Authorization) => {
      let win = this.getAllWindows();
      const savePath = await dialog.showSaveDialog(win[0], {
        defaultPath: fileName, // 使用源文件名作为默认保存文件名
      });
      if (!savePath.canceled && savePath.filePath) {
        let window = BrowserWindow.getAllWindows()[0];
        window.webContents.send('download-start', fileName, savePath.filePath);
         //文件流下载
        const filePath = savePath.filePath;
         const response = await axios.get(downloadUrl, {
          headers: {
             ContentType: 'application/x-www-form-urlencoded',
             Authorization,
           },
           responseType: 'stream',
        });
        const writer = fs.createWriteStream(filePath);
         response.data.pipe(writer);
         return new Promise((resolve, reject) => {
           writer.on('finish', () => {
             console.log('File downloaded successfully:', fs.existsSync(filePath));
        window.webContents.send('download-success', fileName, filePath);
          });
          writer.on('error', () => {
            window.webContents.send('download-failed');
           });
         });
      }
    });

http://www.dtcms.com/a/25763.html

相关文章:

  • 初识MyBatis
  • Java IO
  • 【深度学习】分布偏移纠正
  • PHP场地预定小程序源码
  • 多表关联查询的优化
  • BERT 大模型
  • Grafana——Rocky9安装Grafana相关步骤记录
  • 【文献精读】AAAI24:FacetCRS:打破对话推荐系统中的“信息茧房”
  • 无第三方依赖 go 语言工具库
  • 1688商品评论API接口概述,json数据示例参考
  • Unity 手机屏幕适配
  • 简站主题:简洁、实用、SEO友好、安全性高和后期易于维护的wordpress主题
  • 记一次 Git Fetch 后切换分支为空的情况
  • oppo,汤臣倍健,康冠科技25届春招内推
  • 二、几何体BufferGeometry顶点笔记
  • 【MySQL高级】17 - MySQL中常用工具
  • 3.hadoop3.3.6 HA集群搭建
  • SpringBoot源码解析(十):应用上下文AnnotationConfigServletWebServerApplicationContext构造方法
  • 深度学习-1.简介
  • 深入探索 DeepSeek 在数据分析与可视化中的应用
  • qemu启动aarch64 linux+ buildroot + 应用程序
  • MAVSDK - Custom Mavlink处理
  • mybatis-mp正式改名为xbatis!!!
  • deepseek+ollama+anythingllm在本地搭建个人知识库
  • ollama server启动服务后如何停止
  • HTML之JavaScript DOM(document)编程处理事件
  • Java编程语言:从基础到高级应用的全面探索
  • 火语言RPA--Excel打开文档
  • OpenHarmony 系统性能优化——默认关闭全局动画
  • DIEN:深度兴趣演化网络