1.下载文件
win.webContents.downloadURL(url)
//监听下载动作
win.webContents.session.on('will-download', (event, item, webContents) => {
//拼接要存储的路径
var zipFile = path.join(app.getAppPath(), 'static', item.getFilename())
//设置存储路径 否则会弹出对话框
item.setSavePath(zipFile)
//监听下载过程
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 {
//下载进行中
console.log(`complete:${(item.getReceivedBytes() / item.getTotalBytes() * 100).toFixed(2)}%`)
//任务栏进度条 -1不展示
win.setProgressBar(item.getReceivedBytes() / item.getTotalBytes())
}
}
})
//监听完成
item.once('done', (event, state) => {
})
})
2.zip解压缩
npm i node-unzip-2
//引入 path 模块
const path = require('path')
//引入文件操作模块
var fs = require('fs')
//引入unzip模块
var unzip = require("node-unzip-2")
//解压目标目录
var zipTargetPath = path.join(app.getAppPath(),'static')
//解压文件路径
var zipFile = path.join(app.getAppPath(),'static','test.zip')
console.log('解压目标目录',zipTargetPath)
console.log('解压文件路径',zipFile)
fs.createReadStream(zipFile).pipe(unzip.Extract({ path: zipTargetPath })) //解压时直接会覆盖重名文件
3.关于下载进度条
- electron自带任务栏的下载进度条,适用于后台下载文件
- 如果想把下载进度渲染至页面中,需要用到进程通信,及:主线程发送下载进度,然后渲染线程preload.js中进行监听,然后在preload.js进行页面操作
- preload.js可直接操作Dom,渲染进度条问题不大
- 如果你的网页是独立的且使用vue进行渲染,此种情况无法操作vue的实例,需要手动操作dom