electron 下载文件
主进程
- 在 utils 文件夹下创建 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: ''
}
}
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)
}
})
.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()
})
})
}
const { initDownload } = require('./download')
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('./index.html')
initDownload(win)
}
渲染进程
- 使用
ipcRenderer
向主进程发送消息,消息名称叫download
,传递参数为一个对象,里面包括下载的链接和文件名
const { ipcRenderer } = window.require('electron')
ipcRenderer.send('download', {
downloadPath: 'https://unpkg.com/vue@3.0.7/dist/vue.global.js',
fileName: 'vue.global.js'
})