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

electron展示下载进度条

我们使用electron下载文件时,会发现不像浏览器一样会有地方展示下载进度,这导致下载一些大文件时不知道下载进度到哪里了

下面我们通过electron提供的will-download监听和element-plus中的ElNotificationElProgress组件实现这一功能
在这里插入图片描述

实现逻辑

  1. 触发下载文件这一操作
  2. 监听下载开始、下载进度、下载结束
  3. 根据监听内容操作vnode展示加载进度

1、触发下载文件这一操作

使用electron中ipcMain模块接受页面中发送来的指令

// main.js 部分代码 通过这个打开****.vue界面 
var win = new BrowserWindow();
//  download.js 部分代码
const { ipcMain, dialog } = require('electron')
let filePath = '';// 监听渲染进程发出的download事件
const webContents = win.webContents;ipcMain.on('download', (evt, args) => {const fileArr = args.split("/");let ext = path.extname(args)let filters = [{ name: '全部文件', extensions: ['*'] }]if (ext && ext !== '.') {filters.unshift({name: '',extensions: [ext.match(/[a-zA-Z]+$/)[0]]})}dialog.showSaveDialog(win, {filters,defaultPath:args}).then( res => {if(res.filePath){filePath = res.filePathwebContents.downloadURL(args) // 注意这里必须是下载文件可访问路径。而不是存储路径}})})// vue页面中的逻辑 ***.vueimport { ipcRenderer } from "electron"// 触发var url = '下载地址.***'ipcRenderer.send('download', url)

执行完上面的代码会弹窗另存为下载,会发现下载没有显示进度的地方

2、监听下载开始、下载进度、下载结束

监听webContents中的will-download事件会返回下载相关的一些信息,这里把下载过程中的一些状态和用到的一些参数发送给webContents中打开的页面

// download.js 部分代码webContents.session.on('will-download', (event, item, webContents) => {item.setSavePath(filePath) // 这里是存储路径或者存储文件名称var filName = path.basename(filePath)win.webContents.send('win-will-download',{type:'start',params:{filName}})item.on('updated', (event, state) => {if (state === 'interrupted') {console.log('Download is interrupted but can be resumed')} else if (state === 'progressing') {if (item.isPaused()) {console.log('Download is paused')} else {win.webContents.send('win-will-download',{type:"progress",params:{totalBytes:item.getTotalBytes(),receivedBytes:item.getReceivedBytes()}})}}})item.once('done', (event, state) => {if (state === 'completed') {win.webContents.send('win-will-download',{type:"completed"})console.log('Download successfully')} else {console.log(`Download failed: ${state}`)}})})// ***.vue//download是展示下载进度的组件,下面会有相应的代码 这里通过ref创建响应数据 vue2的话可以通过 Vue.observable API进行创建
import download from "@/components/download/index.vue"
import { ElNotification } from 'element-plus'
import { h, ref } from 'vue'
var totalBytes = ref(0)
var receivedBytes = ref(0)mounted(){ipcRenderer.removeAllListeners('win-will-download')ipcRenderer.on('win-will-download', this.winDownLoadFun)},methods:{winDownLoadFun(event, data) {if (data.type == 'start') {this.notice && this.notice.close && this.notice.close()var progress = h(download, {totalBytes: totalBytes,receivedBytes: receivedBytes,filName: data.params.filName,onClose: () => {totalBytes.value = 0receivedBytes.value = 0this.notice && this.notice.close && this.notice.close()}})this.notice = ElNotification({title: '下载进度',position: 'bottom-right',duration: 0,showClose: false,message: progress,onClose: () => {this.notice = null}})}else if (data.type == 'progress') {totalBytes.value = data.params.totalBytesreceivedBytes.value = data.params.receivedBytes} else if (data.type == 'completed') {receivedBytes.value = totalBytes.value}},} 

3、根据监听内容操作vnode展示加载进度

下面是download/index.vue完整文件

<template><div style="width: 100%;"><div><div @click="$emit('close')" v-if="percentage == 100" style="position: absolute;top: 15px;right: 15px;cursor: pointer;">关闭</div><div class="task-item"><img class="img" src="@/assets/image/zip-1.png"></img><div class="name"><div>{{filName}}</div><div class="progress1">{{limitFormat(receivedBytes.value)}}/{{limitFormat(totalBytes.value)}}</div></div></div><div><el-progress :show-text="false" :percentage="percentage" /></div></div></div>
</template><script>
import { ElMessage, ElProgress } from 'element-plus'
import { ref } from 'vue'
export default {name: 'download',props: {filName:{type:String,default:""},totalBytes: {default() {return ref(0)}},receivedBytes: {default() {return ref(0)}}},computed:{percentage(){return parseFloat((((this.receivedBytes.value / this.totalBytes.value) ||0 )* 100).toFixed(2)) }},watch:{percentage(){if(this.percentage == 100 && this.totalBytes.value != 0){ElMessage({message:"下载完成!",type:"success"})}},},methods: {limitFormat(limit) {var size = "";if (limit < 0.1 * 1024) { //小于0.1KB,则转化成Bsize = limit.toFixed(2) + "B"} else if (limit < 0.1 * 1024 * 1024) { //小于0.1MB,则转化成KBsize = (limit / 1024).toFixed(2) + "KB"} else if (limit < 0.1 * 1024 * 1024 * 1024) { //小于0.1GB,则转化成MBsize = (limit / (1024 * 1024)).toFixed(2) + "MB"} else { //其他转化成GBsize = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB"}var sizeStr = size + ""; //转成字符串var index = sizeStr.indexOf("."); //获取小数点处的索引var dou = sizeStr.substr(index + 1, 2) //获取小数点后两位的值if (dou == "00") { //判断后两位是否为00,如果是则删除00return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)}return size;}},}
</script><style scoped>
.task-item {width: 280px;display: flex;align-items: center;margin-bottom: 6px;
}.progress1 {font-size: 12px;margin-top: -4px;color: #999;
}.task-item i {}.img {width: 32px;height: 32px;display: block;margin-right: 14px;}
</style>

download.js完整代码

const { ipcMain, dialog, shell } = require('electron')
const path = require('path')
const fs = require('fs');
const { type } = require('os');
exports.initDownload = function (win) {let filePath = '';// 监听渲染进程发出的download事件const webContents = win.webContents;ipcMain.on('download', (evt, args) => {const fileArr = args.split("/");let ext = path.extname(args)let filters = [{ name: '全部文件', extensions: ['*'] }]if (ext && ext !== '.') {filters.unshift({name: '',extensions: [ext.match(/[a-zA-Z]+$/)[0]]})}dialog.showSaveDialog(win, {filters,defaultPath:args}).then( res => {if(res.filePath){filePath = res.filePathwebContents.downloadURL(args) // 注意这里必须是下载文件可访问路径。而不是存储路径}})})webContents.session.on('will-download', (event, item, webContents) => {item.setSavePath(filePath) // 这里是存储路径或者存储文件名称var filName = path.basename(filePath)win.webContents.send('win-will-download',{type:'start',params:{filName}})item.on('updated', (event, state) => {if (state === 'interrupted') {console.log('Download is interrupted but can be resumed')} else if (state === 'progressing') {if (item.isPaused()) {console.log('Download is paused')} else {win.webContents.send('win-will-download',{type:"progress",params:{totalBytes:item.getTotalBytes(),receivedBytes:item.getReceivedBytes()}})}}})item.once('done', (event, state) => {if (state === 'completed') {win.webContents.send('win-will-download',{type:"completed"})console.log('Download successfully')} else {console.log(`Download failed: ${state}`)}})})
}

main.js中使用代码
这里的main.js是electron的主进程文件,不是vue相关的问题

const { BrowserWindow } = require("electron");
const {initDownload} = require('@/utils/download.js')
var win = null;
async function createWindow() {win = new BrowserWindow({// 创建相关的参数});// 为创建的win窗口绑定下载事件initDownload(win)
}
createWindow()

相关文章:

electron展示下载进度条

我们使用electron下载文件时&#xff0c;会发现不像浏览器一样会有地方展示下载进度&#xff0c;这导致下载一些大文件时不知道下载进度到哪里了 下面我们通过electron提供的will-download监听和element-plus中的ElNotification和ElProgress组件实现这一功能 实现逻辑 触发…...

Spark 基础操作

Spark 操作 创建操作(Creation Operation) 用于RDD创建工作。RDD创建只有两种方法&#xff0c;一种是来自于内存集合和外部存储系统&#xff0c;另一种是通过转换操作生成的RDD 转换操作(Transformation Operation) 将RDD通过一定的操作变成新的RDD&#xff0c;比如HadoopR…...

VoLTE 微案例:VoLTE 注册失败,I-CSCF 返回 403,HSS(UAR) 返回 5001

目录 1. 问题描述 2. 故障注册流程与正常流程对照 3. 结论 博主wx:yuanlai45_csdn 博主qq:2777137742 想要 深入学习 5GC IMS 等通信知识(加入 51学通信),或者想要 cpp 方向修改简历,模拟面试,学习指导都可以添加博主低价指导哈。 1. 问题描述...

智能财务 | 数据与融合,激发企业财务数智化转型思考

数据与融合&#xff0c;激发企业财务数智化转型思考 用友持续深耕企业财务领域&#xff0c;见证中国企业走过了财务电算化、信息化时代&#xff0c;当下共同经历数智化时代。2023 年度&#xff0c;通过走访标杆企业&#xff0c;与高校教授、权威机构学者共同探讨等形式&#xf…...

docker 下载netcore 镜像

dotnet-docker/README.runtime.md at main dotnet/dotnet-docker GitHub docker pull mcr.microsoft.com/dotnet/runtime:8.0 docker pull mcr.microsoft.com/dotnet/runtime:3.1...

Ajax:请求 响应

Ajax&#xff1a;请求 & 响应 AjaxjQuery的Ajax接口$.get$.post$.ajax PostMan 接口测试getpost Ajax 浏览器中看到的数据&#xff0c;并不是保存在浏览器本地的&#xff0c;而是实时向服务器进行请求的。当服务器接收到请求&#xff0c;就会发回一个响应&#xff0c;此时浏…...

WebForms DataList 控件深入解析

WebForms DataList 控件深入解析 概述 在 ASP.NET WebForms 的众多服务器控件中&#xff0c;DataList 控件是一个功能强大的数据绑定控件&#xff0c;它允许开发者以表格形式展示和操作数据。DataList 控件类似于 Repeater 控件&#xff0c;但提供了更多的内置布局和样式选项…...

【有啥问啥】DINO:一种改进的去噪锚框的端到端目标检测器

DINO&#xff1a;一种改进的去噪锚框的端到端目标检测器 在目标检测领域&#xff0c;DINO&#xff08;DETR with Improved DeNoising Anchor Boxes for End-to-End Object Detection&#xff09;是一种创新的端到端目标检测模型&#xff0c;旨在解决传统目标检测算法中的一些关…...

自由学习记录(15)

Java注解 else if的省略问题&#xff08;可能看花&#xff09; else if也是取最近的if连通&#xff0c;看上去加了{}就可以正常执行了&#xff0c;缩进要命&#xff0c;不提示真容易看错&#xff0c; 组合数公式和数组参数 在 C 中&#xff0c;数组作为函数参数时&#xff0c;…...

Docker 部署 JDK11 图文并茂简单易懂

部署 JDK11 ( Docker ) [Step 1] : 下载JDK11 - JDK 11 | Oracle 甲骨文官网 [Step 2] : jdk11上传服务器/root/jdk11 可自行创建文件夹 进入目录 /root/jdk11 解压文件 tar -zxvf jdk-11.0.22_linux-x64_bin.tar.gz解压后 进入 /root/jdk11/jdk-11.0.22 创建 jre 文件 ./bi…...

Cisco ASAv虚拟防火墙

EVE-NG模拟器使用Cisco防火墙版本ASAv-9.20.3-PLR-Licensed。配置如下&#xff0c;主要是三个方面&#xff0c;配置管理口地址模式DHCP&#xff0c;配置安全级别&#xff1b;第二&#xff0c;开启http服务器&#xff0c;配置允许访问主机的网段和接口&#xff1b;最后配置用户名…...

w~自动驾驶合集6

我自己的原文哦~ https://blog.51cto.com/whaosoft/12286744 #自动驾驶的技术发展路线 端到端自动驾驶 Recent Advancements in End-to-End Autonomous Driving using Deep Learning: A SurveyEnd-to-end Autonomous Driving: Challenges and Frontiers 在线高精地图 HDMa…...

C/C++ H264文件解析

C实现H264文件以及一段H264码流解析&#xff0c;源码如下&#xff1a; h264Parse.h: #ifndef _H264PARSE_H_ #define _H264PARSE_H_#include <fstream>class H264Parse { public:int open_file(const std::string &filename);/*** brief 从文件中读取一个nalu&…...

【Windows】电脑端口明明没有进程占用但显示端口被占用(动态端口)

TOC 一、问题 重启电脑后&#xff0c;启用某个服务显示1089端口被占用。 查看是哪个进程占用了&#xff1a; netstat -aon | findstr "1089"没有输出&#xff0c;但是换其他端口&#xff0c;是可以看到相关进程的&#xff1a; 现在最简单的方式是给我的服务指定另…...

Redis 持久化 问题

前言 相关系列 《Redis & 目录》&#xff08;持续更新&#xff09;《Redis & 持久化 & 源码》&#xff08;学习过程/多有漏误/仅作参考/不再更新&#xff09;《Redis & 持久化 & 总结》&#xff08;学习总结/最新最准/持续更新&#xff09;《Redis & …...

vivado 配置

配置 配置指的是将特定应用数据加载到 FPGA 器件的内部存储器的进程。 赛灵思 FPGA 配置数据储存在 CMOS 配置锁存 (CCL) 中&#xff0c;因此配置数据很不稳定&#xff0c;且在每次 FPGA 器件上电后都必须重 新加载。 赛灵思 FPGA 器件可通过配置引脚&#xff0c;自行…...

Java如何实现PDF转高质量图片

大家好&#xff0c;我是 V 哥。在Java中&#xff0c;将PDF文件转换为高质量的图片可以使用不同的库&#xff0c;其中最常用的库之一是 Apache PDFBox。通过该库&#xff0c;你可以读取PDF文件&#xff0c;并将每一页转换为图像文件。为了提高图像的质量&#xff0c;你可以指定分…...

itemStyle.normal.label is deprecated, use label instead.

itemStyle.normal.label is deprecated, use label instead. normal’hierarchy in label has been removed since 4.0. All style properties are configured in label directly now. 错误写法&#xff1a; itemStyle: {normal: {// color: #00E0FF, // 设置折线点颜色 labe…...

如何在 Linux VPS 上保护 MySQL 和 MariaDB 数据库

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站。 简介 有许多在 Linux 和类 Unix 系统上可用的 SQL 数据库语言实现。MySQL 和 MariaDB 是在服务器环境中部署关系型数据库的两个流行选项…...

CSS 样式 box-sizing: border-box; 用于控制元素的盒模型如何计算宽度和高度

文章目录 box-sizing: border-box; 的含义默认盒模型 (content-box)border-box 盒模型 在微信小程序中的应用示例 在微信小程序中&#xff0c;CSS 样式 box-sizing: border-box; 用于控制元素的盒模型如何计算宽度和高度。具体来说&#xff0c; box-sizing: border-box; 会改…...

eNSP-Cloud(实现本地电脑与eNSP内设备之间通信)

说明&#xff1a; 想象一下&#xff0c;你正在用eNSP搭建一个虚拟的网络世界&#xff0c;里面有虚拟的路由器、交换机、电脑&#xff08;PC&#xff09;等等。这些设备都在你的电脑里面“运行”&#xff0c;它们之间可以互相通信&#xff0c;就像一个封闭的小王国。 但是&#…...

Python爬虫实战:研究feedparser库相关技术

1. 引言 1.1 研究背景与意义 在当今信息爆炸的时代,互联网上存在着海量的信息资源。RSS(Really Simple Syndication)作为一种标准化的信息聚合技术,被广泛用于网站内容的发布和订阅。通过 RSS,用户可以方便地获取网站更新的内容,而无需频繁访问各个网站。 然而,互联网…...

Vue2 第一节_Vue2上手_插值表达式{{}}_访问数据和修改数据_Vue开发者工具

文章目录 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染2. 插值表达式{{}}3. 访问数据和修改数据4. vue响应式5. Vue开发者工具--方便调试 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染 准备容器引包创建Vue实例 new Vue()指定配置项 ->渲染数据 准备一个容器,例如: …...

微信小程序 - 手机震动

一、界面 <button type"primary" bindtap"shortVibrate">短震动</button> <button type"primary" bindtap"longVibrate">长震动</button> 二、js逻辑代码 注&#xff1a;文档 https://developers.weixin.qq…...

有限自动机到正规文法转换器v1.0

1 项目简介 这是一个功能强大的有限自动机&#xff08;Finite Automaton, FA&#xff09;到正规文法&#xff08;Regular Grammar&#xff09;转换器&#xff0c;它配备了一个直观且完整的图形用户界面&#xff0c;使用户能够轻松地进行操作和观察。该程序基于编译原理中的经典…...

云原生玩法三问:构建自定义开发环境

云原生玩法三问&#xff1a;构建自定义开发环境 引言 临时运维一个古董项目&#xff0c;无文档&#xff0c;无环境&#xff0c;无交接人&#xff0c;俗称三无。 运行设备的环境老&#xff0c;本地环境版本高&#xff0c;ssh不过去。正好最近对 腾讯出品的云原生 cnb 感兴趣&…...

Chrome 浏览器前端与客户端双向通信实战

Chrome 前端&#xff08;即页面 JS / Web UI&#xff09;与客户端&#xff08;C 后端&#xff09;的交互机制&#xff0c;是 Chromium 架构中非常核心的一环。下面我将按常见场景&#xff0c;从通道、流程、技术栈几个角度做一套完整的分析&#xff0c;特别适合你这种在分析和改…...

提升移动端网页调试效率:WebDebugX 与常见工具组合实践

在日常移动端开发中&#xff0c;网页调试始终是一个高频但又极具挑战的环节。尤其在面对 iOS 与 Android 的混合技术栈、各种设备差异化行为时&#xff0c;开发者迫切需要一套高效、可靠且跨平台的调试方案。过去&#xff0c;我们或多或少使用过 Chrome DevTools、Remote Debug…...

前端开发者常用网站

Can I use网站&#xff1a;一个查询网页技术兼容性的网站 一个查询网页技术兼容性的网站Can I use&#xff1a;Can I use... Support tables for HTML5, CSS3, etc (查询浏览器对HTML5的支持情况) 权威网站&#xff1a;MDN JavaScript权威网站&#xff1a;JavaScript | MDN...

Mysql故障排插与环境优化

前置知识点 最上层是一些客户端和连接服务&#xff0c;包含本 sock 通信和大多数jiyukehuduan/服务端工具实现的TCP/IP通信。主要完成一些简介处理、授权认证、及相关的安全方案等。在该层上引入了线程池的概念&#xff0c;为通过安全认证接入的客户端提供线程。同样在该层上可…...