Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save file from anchor tag using Electron

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?

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.

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.

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.

like image 573
Joakim Johansson Avatar asked May 04 '15 14:05

Joakim Johansson


2 Answers

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(filePath, pdfContents, 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

like image 193
justin.m.chase Avatar answered Sep 20 '22 00:09

justin.m.chase


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.

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.

like image 45
Joshua Smith Avatar answered Sep 20 '22 00:09

Joshua Smith