avi*_*i12 9 javascript directory download downloadfile electron
我需要将文件下载到Electron程序中的特定位置.
我尝试实现此API但失败了.
然后我尝试实现官方API,但无法实现如何实际开始下载文件.
如何将文件下载到特定位置C:\Folder?
谢谢!
avi*_*i12 25
我最终使用了elecron-dl.
要发送下载请求(来自renderer.js):
ipcRenderer.send("download", {
url: "URL is here",
properties: {directory: "Directory is here"}
});
Run Code Online (Sandbox Code Playgroud)
在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()));
});
});
Run Code Online (Sandbox Code Playgroud)
"下载完成"的监听器在renderer.js,并且看起来像:
const {ipcRenderer} = require("electron");
ipcRenderer.on("download complete", (event, file) => {
console.log(file); // Full file path
});
Run Code Online (Sandbox Code Playgroud)
在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()));
});
Run Code Online (Sandbox Code Playgroud)
在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
});
Run Code Online (Sandbox Code Playgroud)
要允许用户在 Electron 应用程序中下载文件,您需要执行以下操作:
从分区获取默认会话或用户会话。查看会议
一旦您拥有会话对象的实例,您就可以侦听事件,例如will-download当Session用户单击链接下载文件并且将要下载文件时对象上发出的事件。
该will-download事件返回item将要下载的内容。其中item包含必要的事件(下载、失败、暂停等)和必要的方法(保存文件的位置)等。
How to download a file to C:/folder现在,关于?的查询
对此你有两个选择:
item您可以使用从事件获取的对象设置文件的下载位置will-download。使用itemsetSavePath对象上的 方法。如果您想为所有文件设置默认下载位置,那么您可以setDownloadPath在会话对象上使用。那么这将是该会话的默认路径。