electron DownloadItem如何从指定Url中下载文件
const electron = require('electron');
const { session } = electron;
const download = require('electron-dl');
download({
??url: 'http://example.com/file.pdf',
??directory: '~/downloads'
});
2. 在渲染进程中,你可以使用electron-dl模块,结合electron.remote模块获取下载进度和事件。例如:
const electron = require('electron');
const { ipcRenderer, remote } = electron;
const fs = require('fs');
const downloadItem = remote.getCurrentWebContents().session.availableDownloads[0];
downloadItem.on('updated', (event, state) => {
??if (state === 'interrupted') {
? ? console.log('Download is interrupted but can be resumed');
??} else if (state === 'progressing') {
? ? if (downloadItem.isPaused()) {
? ?? ?console.log('Download is paused');
? ? } else {
? ?? ?console.log(`Received bytes: ${downloadItem.getReceivedBytes()}`);
? ? }
??}
});
downloadItem.on('done', (event, state) => {
??if (state === 'completed') {
? ? const filePath = downloadItem.getSavePath();
? ? console.log(`Download is complete, file saved to: ${filePath}`);
??} else {
? ? console.log('Download failed or was canceled');
??}
});