且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

电子-将文件下载到特定位置

更新时间:2023-10-09 11:39:34

我最终使用了 electron-dl

发送一个下载请求(来自 renderer.js ):

ipcRenderer.send("download", {
    url: "URL is here",
    properties: {directory: "Directory is here"}
});

main.js 中,您的代码会看起来像这样:

In the main.js, your code would look something like this:

const {app, BrowserWindow, ipcMain} = require("electron");
const {download} = require("electron-dl");
let window;
app.on("ready", () => {
    window = new BrowserWindow({
        width: someWidth,
        height: someHeight
    });
    window.loadURL(`file://${__dirname}/index.html`);
    ipcMain.on("download", (event, info) => {
        download(BrowserWindow.getFocusedWindow(), info.url, info.properties)
            .then(dl => window.webContents.send("download complete", dl.getSavePath()));
    });
});

下载完成侦听器位于 renderer.js ,如下所示:

The "download complete" listener is in the renderer.js, and would look like:

const {ipcRenderer} = require("electron");
ipcRenderer.on("download complete", (event, file) => {
    console.log(file); // Full file path
});



如果要跟踪下载进度:



main.js

ipcMain.on("download", (event, info) => {
    info.properties.onProgress = status => window.webContents.send("download progress", status);
    download(BrowserWindow.getFocusedWindow(), info.url, info.properties)
        .then(dl => window.webContents.send("download complete", dl.getSavePath()));
});

renderer.js 中:

ipcRenderer.on("download progress", (event, progress) => {
    console.log(progress); // Progress in fraction, between 0 and 1
    const progressInPercentages = progress * 100; // With decimal point and a bunch of numbers
    const cleanProgressInPercentages = Math.floor(progress * 100); // Without decimal point
});