electron-dl模块下载多个不同路径文件为什么最后只有一个
electron-dl模块下载多个不同路径文件为什么最后只有一个electron-dl模块是用于在Electron应用程序中进行文件下载的模块。根据你的描述,下载多个不同路径文件时只有一个文件被保存,可能是因为在循环中重复使用了相同的 options 对象。
为了解决这个问题,你可以在每次下载文件时创建一个新的 options 对象,并为每个文件指定不同的保存路径。以下是一个示例代码:
const { app, BrowserWindow } = require('electron');
const { download } = require('electron-dl');
const path = require('path');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow();
mainWindow.loadURL('https://example.com');
mainWindow.webContents.on('did-finish-load', () => {
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
];
files.forEach(file => {
const options = {
directory: path.join(app.getPath('downloads'), file.directory),
};
download(mainWindow, file.url, options)
.then(dl => {
console.log(`文件已保存至: ${dl.getSavePath()}`);
})
.catch(error => {
console.error('文件下载失败:', error);
});
});
});
}
app.on('ready', () => {
createWindow();
});在这个示例中,我们使用一个包含文件URL和保存目录的数组 files 来指定要下载的文件和它们的保存路径。在循环中,我们为每个文件创建一个新的 options 对象,并将其与对应的文件路径一起传递给 download 函数。
这样,每个文件将会被下载到指定的保存路径中。确保替换示例中的URL和保存目录为实际的文件URL和保存路径。
请注意,electron-dl模块本身并不支持并行下载多个文件,因此在循环中依次下载文件是一个常见的做法。
页:
[1]