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');
           });
         });
      }
    });

8:如果出现调用多次的情况,也可以在preload.js中清除之前的监听

const { contextBridge, ipcRenderer } = require('electron');
var os = require('os');
var mac = '00:00:00:00:00:00';
var networkInterfaces = os.networkInterfaces();
for (var i in networkInterfaces) {
  for (var j in networkInterfaces[i]) {
    if (
      networkInterfaces[i][j]['family'] === 'IPv4' &&
      networkInterfaces[i][j]['mac'] &&
      networkInterfaces[i][j]['mac'] !== '00:00:00:00:00:00' &&
      networkInterfaces[i][j]['address'] !== '127.0.0.1'
    ) {
      mac = networkInterfaces[i][j]['mac'];
    }
  }
}
contextBridge.exposeInMainWorld('electronAPI', {
  downloadSuccess: (callback) => {
    ipcRenderer.removeAllListeners('download-success');
    ipcRenderer.on('download-success', (e, fileName, savePath) => callback(fileName, 
    savePath));
  },
  onDownloadStarted: (name) => ipcRenderer.send('start-download', name),
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值