Vue+Electron监听文件下载后直接打开文件
·
创建Electron应用时,需要在下载完文件后直接打开,且不让它弹出下载目录弹窗。那么可以通过监听下载事件来实现该需求
1. 主进程(main.js)中设置下载监听
// electron/main.js
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron')
const fs = require('fs')
const path = require('path')
// 创建固定下载目录
const downloadsFolder = path.join(app.getPath('downloads'), 'newFolder');
// 确保目录存在
if (!fs.existsSync(downloadsFolder )) {
fs.mkdirSync(downloadsFolder, {recursive: true})
}
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload: path.join(__dirname, 'preload.js'),
}
})
mainWindow.loadURL('http://localhost:8080') // Vue开发服务器地址
mainWindow.maximize(); // 最大化窗口
mainWindow.setMenu(null); // 去掉菜单栏
mainWindow.webContents.openDevTools(); // 打开开发者工具
// 监听下载事件
mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
const filePath = path.join(app.getPath('downloads'), item.getFilename())
// 获取原始文件名
const fileName = item.getFilename();
const filePath = path.join(downloadsFolder, fileName);
// 设置下载路径,不弹出保存对话框
item.setSavePath(filePath)
// 注册下载完成事件
item.once('done', (event, state) => {
if (state === 'completed') {
mainWindow.webContents.send('download-completed', {
fileName: fileName,
path: filePath
});
}
})
})
}
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// 所有窗口关闭时退出应用(非 macOS)
app.on('window-all-closed', () => {
if (process.platform !== 'drawin') {
app.quit();
}
});
// 添加IPC监听,打开文件
ipcMain.handle('open-file', async(event, filePath) => {
try {
await shell.openPath(filePath);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
})
2. 渲染进程/预加载脚本(preload.js)中暴露 electron API
// electron/preload.js
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
onDownloadCompleted: (callback) => ipcRenderer.on('download-completed', callback), //监听下载完成后触发
openFile: (filePath) => ipcRenderer.invoke('open-file', filePath), //打开文件
})
3. Vue组件中触发下载事件
const downloadFile = () => {
// 点击下载某文件,触发下载事件
const fileUrl = 'https://example.com/file.pdf' // 替换为实际需求
//...
}
onMounted(() => {
// 组件中监听,所有类型文件的下载都可以监听到
if (window.electronAPI) {
window.electronAPI.onDownloadCompleted((event, data) => {
console.log('下载完成 data ==>', data);
window.electronAPI.openFile(data.path) //系统程序打开文件
})
}
})
更多推荐

所有评论(0)