我需要将文件下载到我的 Electron 程序中的特定位置。
我尝试实现 this 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 应用程序中下载文件,您需要执行以下操作:
从分区获取默认会话或用户会话。请参阅会议
will-download
之类的事件,当用户单击链接下载文件时,该事件会在 Session
对象上发出,并且该文件将被下载了。will-download
事件返回将要下载的item
。这个item
包含必要的事件(下载、失败、暂停等)和必要的方法(保存文件的位置)等。现在,关于
How to download a file to C:/folder
? 的询问
对此您有 2 个选择:
item
获取的 will-download
对象设置文件的下载位置。在 item对象上使用方法
setSavePath
。setDownloadPath
。那么这将是该会话的默认路径。
正如您自己提到的,电子-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"})
使用 Chromium 的本机网络库发出 HTTP/HTTPS 请求
net.fetch(url).then(async response => {
const fileStream = fs.createWriteStream(file.filePath);
response.arrayBuffer().then(arrayBuffer => {
fileStream.write(Buffer.from(arrayBuffer));
}).finally(() => {
fileStream.close();
});
});