功能描述: electron 实现监听下载进度功能,并将进度实时显示成进度条
electron提供了下载文件的方法:
- mainWindow.webContents.downloadURL(downloadUrl);这个方法类似于静默下载;
- 也可以用动态创建a标签,添加href的方式下载,只是需要手动触发一下;
上面两种方式都可以在主进程中监听下载情况:
//mainwin.js
let value = 0
mainwinow.webContents.session.on(
'will-download',(evt,item,webContents) =>{
item.on('updated',(evt,state)=>{
if('progressing' === state){
//此处 用接收到的字节数和总字节数求一个比例 就是进度百分比
if(item.getRecevicedBytes() && item.getTotalBytes()) {
value = parseInt(
100*(
item.getRecevicedBytes()/item.getTotalBytes()
)
)
}
// 把百分比发给渲染进程进行展示
mainWindow.webContents.send('updateProgressing', value);
}
})
}
)
//在负责渲染的vue文件created生命周期函数中接受消息,做相应处理
ipcRenderer.removeAllListeners('updateProgressing');
ipcRenderer.on('updateProgressing', (e, value) => {
this.$nextTick(() => {
this.downloadStatus = true;
this.percentage = value;
});
效果如下:item.getRecevicedBytes() && item.getTotalBytes()
这个要注意判断,刚开始总数为0 ,相除会出现NaN,别显示在进度条上,当心测试甩单过来
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SN1gL0Ot-1612410126218)(C:\Users\youdu\AppData\Roaming\Typora\typora-user-images\image-20210204113333296.png)]