Save file from anchor tag using Electron

Is it possible to have regular anchor tags pointing to files that open a dialog box for saving a file? Like in a web browser.

For instance:

<a download href="documents/somefile.pdf">Download</a> 

And having this anchor tag that launches the Save File dialog when clicked?

I tried using file://absolute-path-to-the-dir/documents/somefile.pdf , and he wants to open the file in the application, and not download it.

Update: In a later version of Electron than I used when I wrote this question, the behavior is the way I want, a window will open that asks the user to save the file.

However, in the case of external links and in order to save the Electron window only for internal links and open external ones in the default OS selection, Joshua Smith's answer can do just that.

+6
source share
2 answers

What I do is double.

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

This is so that whenever a page in my application wants to open a new window, this will happen in a real browser. It is also useful for opening PDF files, etc.

Then I just make sure that any download links use target = _blank or window.open (), and the download will occur in a user browser.

+2
source

In a script, you can use the file save dialog 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:

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

+6
source

Source: https://habr.com/ru/post/986511/


All Articles