How do you automatically download a file in javascript?

If it's an actual file (something that won't simply display in your browser like a JPG file) then you could use a javascript or meta redirect.

<script> document.location.href = 'yourfile.exe'; </script>

or

<meta http-equiv="refresh" content="0; url=yourfile.exe">

But I am wondering if you might be talking about the user being asked if they want to open or save a file (whether it's a JPG or whatever?)


Another way to do it :

var a = document.createElement('a');
a.setAttribute('href', dataUri);
a.setAttribute('download', filename);

var aj = $(a);
aj.appendTo('body');
aj[0].click();
aj.remove();