demo 源码:23.08.zip
功能描述:
- 点击 send msg 按钮,弹出保存提示框,用户自定义下载路径
- 下载 downloadUrl 到指定位置
- 渲染进程中要求实时展示下载进度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>23.08 test download</title>
</head>
<body>
<h1>hello world</h1>
<button id="btn">send msg</button>
<!-- 添加进度条元素 -->
<progress id="downloadProgress" value="0" max="100"></progress>
<script src="./renderer.js"></script>
</body>
</html>
const { ipcRenderer } = require('electron')
const btn = document.querySelector('#btn')
const downloadProgress = document.querySelector('#downloadProgress') // 一个进度条元素或其他你用来显示进度的UI元素
const downloadUrl = "https:xxxx/xxxx/xxxx.exe"
btn.addEventListener('click', () => {
ipcRenderer.invoke('msg-from-renderer', downloadUrl)
})
ipcRenderer.on('download-progress', (event, progress) => {
console.log('progress:', progress)
downloadProgress.value = progress * 100
})
const { app, BrowserWindow, ipcMain, dialog } = require('electron')
const fs = require('fs')
const https = require('https')
let win
function createWin() {
win = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
})
win.loadFile('./index.html')
win.webContents.openDevTools()
}
ipcMain.handle('msg-from-renderer', (_, downloadUrl) => {
// 使用 dialog.showSaveDialog 获取用户想要保存文件的位置
dialog.showSaveDialog({
title: '选择保存位置',
defaultPath: 'WmLossPreventService.exe' // 默认的文件名,你可以根据实际情况修改
}).then(result => {
if (!result.canceled) {
const file = fs.createWriteStream(result.filePath);
https.get(downloadUrl, function (response) {
const totalBytes = parseInt(response.headers['content-length'], 10);
let downloadedBytes = 0;
response.on('data', (chunk) => {
downloadedBytes += chunk.length;
const progress = downloadedBytes / totalBytes;
win.webContents.send('download-progress', progress);
});
response.pipe(file);
file.on('finish', function () {
file.close();
console.log('App downloaded!');
});
});
}
})
})
app.whenReady().then(() => {
console.log('app ready')
createWin()
})
{
"name": "23.08",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^26.0.0"
}
}