How do you automatically download a file in javascript?

29,411

Solution 1

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?)

Solution 2

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();

Solution 3

Another option which is pure javascript is:

const downloadFile = (file) => {
  const element = document.createElement('a');
  element.setAttribute('href', 'Download Btn');
  element.setAttribute('download', file);

  element.style.display = 'none';

  document.body.appendChild(element);

  element.click();
  document.body.removeChild(element);
}

And then you can call the function on load:

downloadFile(/*pass your file here*/);
Share:
29,411
Zinger
Author by

Zinger

Just for fun.

Updated on March 09, 2021

Comments

  • Zinger
    Zinger about 3 years

    So, I've been looking and trying to find a way to download a file automatically right when somebody goes onto my site. I've tried using an a tag to download, and it works, you just have to click to download it. Like so...

    <a href="pic.jpg" download>Download</a>

    But I don't want that. I want it to automatically download with no click. I need some help please!

  • Thanasis
    Thanasis almost 5 years
    Wonderful to see both methods. The above method won't open a .jpg or a .pdf in the browser ! Woenderful
  • Era
    Era over 3 years
    This solution is so elegant!