15

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!

4
  • So you mean there would not be anything else on your website and just when user clicks the url of your website, the file should get downloaded? Commented Apr 28, 2016 at 1:17
  • Sorry - Answered but didn't realise you already tried the download attribute. Still, this is best done server side, using a 'Content-disposition: attachment' header when serving the file Commented Apr 28, 2016 at 1:21
  • 1
    You can bind a function on html <a href="pic.jpg" onclick="download('pic.jpg')">Download</a> and download function open a window with file url Commented Apr 28, 2016 at 1:42
  • Possible duplicate of Download a file using Javascript Commented Apr 28, 2016 at 3:39

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

Comments

10

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

1 Comment

Wonderful to see both methods. The above method won't open a .jpg or a .pdf in the browser ! Woenderful
4

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*/); 

1 Comment

what is the type of file? I tried typing it as "File" but got an error

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.