electron 文件下载并监听进度

747 阅读1分钟

1.使用electron的webContents.downloadURL下载

//下载文件方法
downloadBigFile(data) {
    //获取Window 
    let mainWindow = CoreElectronWindow.getMainWindow()
    //触发下载
    mainWindow.webContents.downloadURL(data.fileUrl)
    //保存文件的路径
    let filePath = data.filePath;

    //下载
    const downloadListener = (event, item) => {
        //保存到指定路径
        item.setSavePath(filePath);
        // 监听下载进度
        item.on('updated', () => {
            let progress = (item.getReceivedBytes() / item.getTotalBytes()) * 100;
            // TODO: 更新下载进度条或其他 UI
            // 调用进度回调函数传递进度
            mainWindow.send('downloadBigFileProgress', parseInt(progress.toFixed(0)));
        });

        // 监听下载完成事件
        item.on('done', (event, state) => {
            if (state === 'completed') {
                // TODO: 下载完成处理逻辑
                // 调用完成回调函数传递完成状态
                mainWindow.send('downloadBigFileProgress', 100, filePath);
                //打开文件
                shell.openPath(filePath)
            } else {
                // TODO: 下载失败处理逻辑
                // 调用完成回调函数传递失败状态
                mainWindow.send('downloadBigFileProgress', -1);
            }
            //移除监听
            mainWindow.webContents.session.removeListener('will-download', downloadListener);
        });
    }

    //下载回调
    mainWindow.webContents.session.on('will-download', downloadListener);

}

2.在页面中调用

//下载文件事件
async download() {
    let that = this;
    //下载进度
    this.downProgress = 0

    //文件下载地址
    let url = '文件下载地址';
    //文件名
    let fileName = 'test.mp4',
    //文件存放路径
    let filePath = '/w/download'

    let temp = {
      fileUrl: url,
      fileName: fileName,
      filePath: filePath
    }

    //下载文件downloadBigFile 是通过服务调用downloadBigFile方法
    ipc.invoke(ipcApiRoute.downloadBigFile, temp).then(result => {
      console.log('res')
    })

    //监听载进度
    ipc.on('downloadBigFileProgress', (event, progress, savePath) => {
      console.log('progress', progress)
      this.downProgress = progress
    });
},