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

相关文章:

  • 【Docker】容器被停止/删除的方式及命令:全面解析与实践指南
  • 线上就医全流程医药机构接入文档接口代码-医保就医接口php-demo版本
  • 缓存三大问题及其解决方案
  • 大语言模型常用微调与基于SFT微调DeepSeek R1指南
  • LabVIEW的吞雨测控系统
  • redis基础命令
  • 基于Java+SpringBoot+Vue的前后端分离的校园闲置物品交易网站
  • K8s 证书认知(K8s Certificate Awareness)
  • 前x-ai首席科学家karpathy的从零构建ChatGPT视频学习笔记--8000字长图文笔记预警(手打纯干货,通俗易懂)
  • 【智慧校园】分体空调节能监管:打造高效节能的学习环境
  • 深度学习-1.简介
  • 【Rust中级教程】1.10. 引用及内部可变性(简单回顾):引用、内部可变性、`Cell`类型及相关操作
  • Docker 安装和配置 Nginx 详细图文教程
  • 基于Java+Swing+Mysql实现旅游管理信息系统
  • 使用 Openpyxl 操作 Excel 文件详解
  • 统信服务器操作系统V20 1070A 安装docker新版本26.1.4
  • 【数据分享】1929-2024年全球站点的逐年降雪深度数据(Shp\Excel\免费获取)
  • python爬虫系列课程1:初识爬虫
  • 大模型工具大比拼:SGLang、Ollama、VLLM、LLaMA.cpp 如何选择?
  • 什么是语料清洗、预训练、指令微调、强化学习、内容安全; 什么是megatron,deepspeed,vllm推理加速框架
  • HTTP的“对话”逻辑:请求与响应如何构建数据桥梁?
  • 【深度学习】预训练和微调概述
  • 自动化测试框架搭建-单次接口执行-三部曲
  • 【阮一峰】2.数组
  • DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方DeepSeek接入)
  • 【Java Card】Applet 使用Shareable进行数据分享以及部分问题处理
  • 国产FPGA开发板选择
  • com.typesafe.config
  • Ubuntu学习备忘
  • 【C++】— 掌握STL vector 类:“Vector简介:动态数组的高效应用”