当前位置: 首页 > 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.mrgr.cn/news/91536.html

相关文章:

  • c# -01新属性-模式匹配、弃元、析构元组和其他类型
  • Linux驱动学习(二)--字符设备
  • docker修改镜像默认存储路径(基于 WSL2 的迁移方法)
  • Ubuntu20.04安装IsaacSim4.5与IsaacLab2.0
  • 2015年下半年试题二:论软件系统架构风格
  • wps中的js开发
  • Web后端 Tomcat服务器
  • 15. 三数之和(LeetCode 热题 100)
  • Flutter
  • 【亚马逊开发者账号02】终审问题SA+review_Pre-review+Doc.xlsx
  • 单元测试方法的使用
  • 力扣 跳跃游戏 II
  • 计算机视觉:卷积神经网络(CNN)基本概念(二)
  • 大模型 + cursor应用案例
  • 基于Django快递物流管理可视化分析系统(完整系统源码+数据库+详细开发文档+万字详细论文+答辩PPT+详细部署教程等资料)
  • QT移植,交叉编译至泰山派RK3566开发板,.pro文件解析
  • 计算机视觉:神经网络实战之手势识别(附代码)
  • Node-Red
  • 探讨如何加快 C# 双循环的速度效率
  • 服务器装机可用的基本操作