繁体   English   中英

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

[英]Electron - Download a file to a specific location

我需要将文件下载到Electron程序中的特定位置。
我尝试实现此API但失败了。
然后我尝试实现官方API ,但无法实现如何实际开始下载文件。

如何将文件下载到特定位置,例如C:\\Folder
谢谢!

我最终使用了电子dl
要发送下载请求(来自renderer.js ):

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

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

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 ,看起来像:

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
});

正如你自己提到的那样, electron-dl似乎是流行的方式。 主要来自github页面: npm i -S electron-dl

const {BrowserWindow} = require('electron');
const {download} = require('electron-dl');
download(BrowserWindow.getFocusedWindow(), "http://url-to-asset", {directory:"c:/Folder"})

要允许用户在Electron应用程序中下载文件,您需要执行以下操作:

  1. 从分区获取默认会话或用户会话。 会议

  2. 获得会话对象的实例后,您可以监听当用户单击链接下载文件并将要下载文件时在Session对象上发出的will-download等事件。

  3. will-download事件返回的item ,其将被下载。 item包含必要的事件(下载,失败,暂停等)和必要的方法(保存文件的位置)等。

现在,关于How to download a file to C:/folder

你有2个选择:

  1. 您可以要求用户设置下载位置(默认行为)
  2. 您可以使用item对象设置文件的下载位置,您可以从事件中will-downloadwill-download 项目对象上使用方法setSavePath

如果您想要为所有文件设置默认下载位置,则可以在会话对象上使用setDownloadPath 那么这将是该会话的默认路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM