主要通过 Electron
中 will-download
事件和主进程和渲染进程之间的通信,实时监听下载进度
main/index.js
mainWindow.webContents.session.on('will-download', (e, item) => {
//获取文件的总大小
const totalBytes = item.getTotalBytes();
//设置文件的保存路径,此时默认弹出的 save dialog 将被覆盖
const rootPath = app.getPath("userData") + "/channel";
const filePath = path.join(rootPath, item.getFilename());
item.setSavePath(filePath);
//获得下载链接
let url = item.getURL()
//监听下载过程,计算并设置进度条进度
item.on('updated', () => {
let process = item.getReceivedBytes() / totalBytes
process = Math.round(process * 100)
mainWindow.setProgressBar(process);
//向渲染进程发送下载进度
sendMessage(url, process)
});
//监听下载结束事件
item.on('done', (e, state) => {
//如果窗口还在的话,去掉进度条
if (!mainWindow.isDestroyed()) {
mainWindow.setProgressBar(-1);
}
//下载被取消或中断了
if (state == 'interrupted') {
electron.dialog.showErrorBox('下载失败', `文件