Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download image with JavaScript

Right now I have a canvas and I want to save it as PNG. I can do it with all those fancy complicated file system API, but I don't really like them.

I know if there is a link with download attribute on it:

<a href="img.png" download="output.png">Download</a> 

it will download the file if the user clicks on it. Therefore I came up with this:

$("<a>")     .attr("href", "img.png")     .attr("download", "output.png")     .appendTo("body")     .click()     .remove(); 

Demo: http://jsfiddle.net/DerekL/Wx7wn/

However, it doesn't seem to work. Does it have to be trigger by an user action? Or else why didn't it work?

like image 818
Derek 朕會功夫 Avatar asked Jun 26 '13 04:06

Derek 朕會功夫


People also ask

How do I download an image from a website?

To save an image from a website in Chrome, users can usually just right-click on it and select “Save image” from the menu.

How do I download an image from react JS?

To download a file with React. js, we can add the download attribute to an anchor element. We just add the download prop to do the download. If we don't want to use an anchor element, we can also use the file-saver package to download our file.

Does JavaScript have a download?

No, you don't have to install JavaScript. Web Browsers such as Chrome have JavaScript automatically built into it - in other words, you always have JavaScript capabilities, so there is no extra software you have to download and install in order to use JavaScript.


1 Answers

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a'); a.href = "img.png"; a.download = "output.png"; document.body.appendChild(a); a.click(); document.body.removeChild(a); 

Demo

like image 88
Oriol Avatar answered Sep 27 '22 21:09

Oriol