demo 源码:23.08.zip

    功能描述:

    1. 点击 send msg 按钮,弹出保存提示框,用户自定义下载路径
    2. 下载 downloadUrl 到指定位置
    3. 渲染进程中要求实时展示下载进度

    image.png
    image.png

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>23.08 test download</title>
    7. </head>
    8. <body>
    9. <h1>hello world</h1>
    10. <button id="btn">send msg</button>
    11. <!-- 添加进度条元素 -->
    12. <progress id="downloadProgress" value="0" max="100"></progress>
    13. <script src="./renderer.js"></script>
    14. </body>
    15. </html>
    1. const { ipcRenderer } = require('electron')
    2. const btn = document.querySelector('#btn')
    3. const downloadProgress = document.querySelector('#downloadProgress') // 一个进度条元素或其他你用来显示进度的UI元素
    4. const downloadUrl = "https:xxxx/xxxx/xxxx.exe"
    5. btn.addEventListener('click', () => {
    6. ipcRenderer.invoke('msg-from-renderer', downloadUrl)
    7. })
    8. ipcRenderer.on('download-progress', (event, progress) => {
    9. console.log('progress:', progress)
    10. downloadProgress.value = progress * 100
    11. })
    1. const { app, BrowserWindow, ipcMain, dialog } = require('electron')
    2. const fs = require('fs')
    3. const https = require('https')
    4. let win
    5. function createWin() {
    6. win = new BrowserWindow({
    7. webPreferences: {
    8. nodeIntegration: true,
    9. contextIsolation: false,
    10. }
    11. })
    12. win.loadFile('./index.html')
    13. win.webContents.openDevTools()
    14. }
    15. ipcMain.handle('msg-from-renderer', (_, downloadUrl) => {
    16. // 使用 dialog.showSaveDialog 获取用户想要保存文件的位置
    17. dialog.showSaveDialog({
    18. title: '选择保存位置',
    19. defaultPath: 'WmLossPreventService.exe' // 默认的文件名,你可以根据实际情况修改
    20. }).then(result => {
    21. if (!result.canceled) {
    22. const file = fs.createWriteStream(result.filePath);
    23. https.get(downloadUrl, function (response) {
    24. const totalBytes = parseInt(response.headers['content-length'], 10);
    25. let downloadedBytes = 0;
    26. response.on('data', (chunk) => {
    27. downloadedBytes += chunk.length;
    28. const progress = downloadedBytes / totalBytes;
    29. win.webContents.send('download-progress', progress);
    30. });
    31. response.pipe(file);
    32. file.on('finish', function () {
    33. file.close();
    34. console.log('App downloaded!');
    35. });
    36. });
    37. }
    38. })
    39. })
    40. app.whenReady().then(() => {
    41. console.log('app ready')
    42. createWin()
    43. })
    1. {
    2. "name": "23.08",
    3. "version": "1.0.0",
    4. "description": "",
    5. "main": "index.js",
    6. "scripts": {
    7. "test": "echo \"Error: no test specified\" && exit 1"
    8. },
    9. "author": "",
    10. "license": "ISC",
    11. "dependencies": {
    12. "electron": "^26.0.0"
    13. }
    14. }