使用Electron从锚标记中保存文件

Joa*_*son 7 javascript electron

是否可以将常规锚标记指向打开用于保存文件的对话框的文件?就像网络浏览器一样.

例如:

<a download href="documents/somefile.pdf">Download</a>
Run Code Online (Sandbox Code Playgroud)

让click-tag在点击时触发Save文件对话框?

我尝试过使用file://absolute-path-to-the-dir/documents/somefile.pdf它想要在应用程序中打开文件而不是下载它.

更新:在Electron的后续版本中,我在编写此问题时使用的行为就像我想要的那样,会打开一个窗口,要求用户保存文件.

但是,在外部链接的情况下,想要保留Electron窗口仅用于内部链接并在默认操作系统选项中打开外部链接,Joshua Smith的答案可以做到这一点.

jus*_*ase 7

在脚本中,您可以使用对话框模块使用保存文件对话框:

var fs = require('fs');
var dialog = require('dialog');
dialog.showSaveDialog(options, function (filePath) {
    fs.writeFile(filePath, pdfContents, function (err) {
        if(err) console.error(err);
    });
});
Run Code Online (Sandbox Code Playgroud)

这是文档:

https://github.com/atom/electron/blob/master/docs/api/dialog.md#dialogshowsavedialogbrowserwindow-options-callback


Jos*_*ith 3

我正在做的事情有两个方面。

mainWindow.webContents.on('new-window', function(event, url) {
    event.preventDefault();
    console.log("Handing off to O/S: "+url);
    shell.openExternal(url);
});
Run Code Online (Sandbox Code Playgroud)

这样,每当我的应用程序中的页面想要打开一个新窗口时,这就会在实际的浏览器中发生。这对于打开 PDF 等也很有用。

然后我只需确保任何下载链接都使用 target=_blank 或 window.open() 并且下载将在用户的浏览器中进行。