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