electron 下载文件

491 阅读1分钟

创建 download.js,复制下面代码 `const { ipcMain, dialog, shell } = require('electron') const path = require('path')

exports.initDownload = function (win) { let downloadObj = { downloadPath: '', // 要下载的链接或文件 fileName: '', // 要保存的文件名,需要带文件后缀名 savedPath: '' // 要保存的路径 } function resetDownloadObj() { downloadObj = { downloadPath: '', fileName: '', savedPath: '' } } // 监听渲染进程发出的download事件 ipcMain.on('download', (evt, args) => { downloadObj.downloadPath = args.downloadPath downloadObj.fileName = args.fileName let ext = path.extname(downloadObj.fileName) let filters = [{ name: '全部文件', extensions: ['*'] }] if (ext && ext !== '.') { filters.unshift({ name: '', extensions: [ext.match(/[a-zA-Z]+$/)[0]] }) } // 弹出另存为弹框,用于获取保存路径 dialog .showSaveDialog(win, { filters, defaultPath: downloadObj.fileName }) .then((result) => { downloadObj.savedPath = result.filePath if (downloadObj.savedPath) { win.webContents.downloadURL(downloadObj.downloadPath) // 触发will-download事件 } }) .catch(() => {}) })

win.webContents.session.on('will-download', (event, item) => { //设置文件存放位置 item.setSavePath(downloadObj.savedPath) 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(Received bytes: ${item.getReceivedBytes()}) } } }) item.once('done', (event, state) => { if (state === 'completed') { console.log('Download successfully') shell.showItemInFolder(downloadObj.savedPath) // 下载成功后打开文件所在文件夹 } else { console.log(Download failed: ${state}) } resetDownloadObj() }) }) } `

  • main.js中引入上面导出的函数 `const { initDownload } = require('./download')

function createWindow() { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) win.loadFile('./index.html') initDownload(win) // 初始化下载,这里需要传入创建的BrowserWindow对象 }`

渲染进程

  • 使用ipcRenderer向主进程发送消息,消息名称叫download,传递参数为一个对象,里面包括下载的链接和文件名

`const { ipcRenderer } = window.require('electron')

ipcRenderer.send('download', { downloadPath: 'unpkg.com/vue@3.0.7/d…', // 下载链接(以下载vue文件为例) fileName: 'vue.global.js' // 下载文件名,需要包含后缀名 })`

  • 发送download消息后,会弹出另存为弹框

image.png

  • 选择路径保存后,就会开始下载