electron-dl用于在Electron中下载多个文件

2023-12-28 13:34:21

electron-dl用于在Electron中下载多个文件

const { app, BrowserWindow, ipcMain } = require('electron');
const { download } = require('electron-dl');
const path = require('path');
 async function createWindow() {
??const mainWindow = new BrowserWindow();
? ?mainWindow.loadURL('https://example.com');
? ?mainWindow.webContents.on('did-finish-load', async () => {
? ? const files = [
? ?? ?{ url: 'https://example.com/file1.ext', directory: 'path/to/save/file1' },
? ?? ?{ url: 'https://example.com/file2.ext', directory: 'path/to/save/file2' },
? ?? ?// Add more files with their respective URLs and directories
? ? ];
? ???for (const file of files) {
? ?? ?const options = {
? ?? ???directory: path.join(app.getPath('downloads'), file.directory),
? ?? ?};
? ?? ? try {
? ?? ???const dl = await download(mainWindow, file.url, options);
? ?? ???console.log(`File saved to: ${dl.getSavePath()}`);
? ?? ?} catch (error) {
? ?? ???console.error('File download failed:', error);
? ?? ?}
? ? }
? ???mainWindow.close();
??});
}
 app.on('ready', createWindow);

在这个更新的代码中,我们使用了 electron-dl 模块的 download 函数来实现文件下载。我们在主窗口加载完成后,通过循环遍历文件列表,使用 await 关键字等待文件下载完成。下载成功后,我们打印出文件保存的路径。如果下载失败,则打印错误信息。
请注意,您需要在 files 数组中添加要下载的文件的URL和目录。确保您已经安装了 electron-dl 模块。

npm install?electron-dl?

文章来源:https://blog.csdn.net/airen3339/article/details/135261764
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。