const fs = require('fs') const path = require('path') import { ElectronDownloadManager } from 'electron-dl-manager' import { dialog } from 'electron' const manager = new ElectronDownloadManager() export default async function ({ app, shell, BrowserWindow, ipcMain }) { const userDataPath = app.getPath('userData') //默认浏览器打开url ipcMain.on('open-url-browser', (e, url) => { shell.openPath(url) }) //使用默认应用打开本地文件 ipcMain.on('open-path-app', (e, path) => { shell.openExternal(path) }) //复制文件 ipcMain.on('copy-file-default', (e, { source, destination }) => { copyFile(source, destination, (error, filePath) => { e.reply('copy-file-default-reply', { error, filePath }) }) }) //下载文件 ipcMain.on('download-file-default', (e, url) => { createFolder('selfFile').then(async () => { const browserWindow = BrowserWindow.fromId(e.sender.id) const id = await manager.download({ window: browserWindow, url: url, directory: userDataPath + '/selfFile/', callbacks: { onDownloadStarted: async ({ id, item, webContents }) => { // Do something with the download id }, onDownloadProgress: async ({ id, item, percentCompleted }) => { browserWindow.webContents.invoke('download-progress', { id, percentCompleted, // Get the number of bytes received so far bytesReceived: item.getReceivedBytes() }) }, onDownloadCompleted: async ({ id, item }) => { console.log(item) }, onDownloadCancelled: async () => {}, onDownloadInterrupted: async () => {}, onError: (err, data) => {} } }) }) }) /**另存为... * 接收渲染进程 保存文件的 的通知 * @param {Object} event * @param {String} url 下载链接 * @param {String} fileName 文件名称包括后缀名,例如图1.png */ ipcMain.on('save-as', function (event, url, fileName) { let win = BrowserWindow.getFocusedWindow(); //通过扩展名识别文件类型 let filters = [{ name: '全部文件', extensions: ['*'] }] let ext = path.extname(fileName) //获取扩展名 if (ext && ext !== '.') { const name = ext.slice(1, ext.length) if (name) { filters.unshift({ name: '', extensions: [name] }) } } let filePath = null //用户选择存放文件的路径 //1- 弹出另存为弹框,用于获取保存路径 dialog .showSaveDialog(win, { title: '另存为', filters, defaultPath: fileName }) .then((result) => { //点击保存后开始下载 filePath = result.filePath if (filePath) { win.webContents.downloadURL(url) // 触发will-download事件 } }) .catch(() => { console.log('另存为--catch') }) //2- 准备下载的时候触发 win.webContents.session.once('will-download', (event, item, webContents) => { if (!filePath) return //设置下载项的保存文件路径 item.setSavePath(filePath) }) }) function copyFile(source, destination, callback) { let path = userDataPath + '\\selfFile\\' + destination createFolder('selfFile').then(() => { const readStream = fs.createReadStream(source) const writeStream = fs.createWriteStream(path) readStream.on('error', (error) => { callback(error, null) }) writeStream.on('error', (error) => { callback(error, null) }) writeStream.on('close', () => { callback(null, path) }) readStream.pipe(writeStream) }) } function createFolder(folderName) { return new Promise((resolve, reject) => { const folderPath = path.join(userDataPath, folderName) // 异步检查文件夹是否存在,不存在则创建 fs.access(folderPath, fs.constants.F_OK, (err) => { if (err) { fs.mkdir(folderPath, { recursive: true }, (mkdirErr) => { if (mkdirErr) { console.error(mkdirErr) reject() } else { console.log(`Folder ${folderName} created successfully.`) resolve() } }) } else { console.log(`Folder ${folderName} already exists.`) resolve() } }) }) } }