Is it possible to have regular anchor tags pointing to files that open a dialog for saving the file? Like a web browser would.
是否可以将常规锚标记指向打开用于保存文件的对话框的文件?就像网络浏览器一样。
For example:
<a download href="documents/somefile.pdf">Download</a>
And having that anchor-tag triggering a Save file-dialog on click?
让click-tag在点击时触发Save文件对话框?
I've tried using file://absolute-path-to-the-dir/documents/somefile.pdf
and it wants to open the file in the application rather than download it.
我尝试使用file://absolute-path-to-the-dir/documents/somefile.pdf,它想要在应用程序中打开文件而不是下载它。
Update: In a later version of Electron than I used when I wrote this question the behaviour is as I want it to be, a window opens that asks the user to save the file.
更新:在Electron的后续版本中,我在编写此问题时使用的行为就像我想要的那样,会打开一个窗口,要求用户保存文件。
However, in the case of external links and wanting to keep the Electron window only for internal links and open the external ones in the default OS choice, the answer by Joshua Smith can do exactly that.
但是,在外部链接的情况下,想要保留Electron窗口仅用于内部链接并在默认操作系统选项中打开外部链接,Joshua Smith的答案可以做到这一点。
2 个解决方案
#1
What I'm doing is two-fold.
我正在做的是双重的。
mainWindow.webContents.on('new-window', function(event, url) {
event.preventDefault();
console.log("Handing off to O/S: "+url);
shell.openExternal(url);
});
That is there so that whenever a page in my app wants to open a new window, that'll happen in an actual browser. This is also good for opening PDFs and such.
就是这样,只要我的应用中的某个页面想要打开一个新窗口,就会发生在实际的浏览器中。这也适用于打开PDF等。
Then I just make sure that any download links use target=_blank or window.open() and the download will happen in the user's browser.
然后我确保所有下载链接都使用target = _blank或window.open(),并且下载将在用户的浏览器中进行。
#2
In script you can use the save file dialog by using the dialog module:
在脚本中,您可以使用对话框模块使用保存文件对话框:
var fs = require('fs');
var dialog = require('dialog');
dialog.showSaveDialog(options, function (filePath) {
fs.writeFile(pdfContents, filePath, function (err) {
if(err) console.error(err);
});
});
Here is the documentation:
这是文档:
#1
What I'm doing is two-fold.
我正在做的是双重的。
mainWindow.webContents.on('new-window', function(event, url) {
event.preventDefault();
console.log("Handing off to O/S: "+url);
shell.openExternal(url);
});
That is there so that whenever a page in my app wants to open a new window, that'll happen in an actual browser. This is also good for opening PDFs and such.
就是这样,只要我的应用中的某个页面想要打开一个新窗口,就会发生在实际的浏览器中。这也适用于打开PDF等。
Then I just make sure that any download links use target=_blank or window.open() and the download will happen in the user's browser.
然后我确保所有下载链接都使用target = _blank或window.open(),并且下载将在用户的浏览器中进行。
#2
In script you can use the save file dialog by using the dialog module:
在脚本中,您可以使用对话框模块使用保存文件对话框:
var fs = require('fs');
var dialog = require('dialog');
dialog.showSaveDialog(options, function (filePath) {
fs.writeFile(pdfContents, filePath, function (err) {
if(err) console.error(err);
});
});
Here is the documentation:
这是文档: