Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron issue with download attribute

Tags:

Following my previous question here,

I have a desktop application using Electron platform and Javascript where I am converting an HTML5 canvas to JPEG using:

<a id="download" download="Path.jpg">Download JPG</a>

then,

function download(){ 
    var dt = canvas.toDataURL('image/jpeg');
    this.href=dt; 
}
document.getElementById('download').addEventListener('click', download, false);

This refreshes my whole application. How can I change this behavior, such that the page does not refresh when the download attribute is clicked?

like image 517
rrz0 Avatar asked Dec 15 '17 07:12

rrz0


2 Answers

I can think of this two snippets, one using blob and one using the download element. external-library: FileSave.js

// this one use FileSaver.js library
canvas.toBlob(function(blob) {
    saveAs(blob, "pretty image.png");
});

// or this way using download element.
// here you can encode your image-data and then send it.
var download = document.getElementById('download');
download.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(imageData));
download.setAttribute('download', 'file.jpg');

also I found this one just now, electron specific solution : Saving files locally with electron

like image 174
nullqube Avatar answered Sep 23 '22 12:09

nullqube


Edit your anchor tag a bit

<a id="download" download="Path.jpg" target="_blank" onClick="download();">Download JPG</a>

And then your download function

function download(event){
    event.currentTarget.href = canvas.toDataURL('image/jpeg');
}

This might help

like image 45
Ashok Vishwakarma Avatar answered Sep 20 '22 12:09

Ashok Vishwakarma