ßamuel
ßamuel

Reputation: 35

How do I make a button that will download a file

I'm attempting to make a button that will download an image file upon pressing, but what I've made will only take me to the file itself.

Html:

<button onclick="file()">Click me, i'll download an image</button>

Javascript:

function file() {
    const anchor = document.createElement("a");
    anchor.href = "dingus.png";
    anchor.download = "dingus.png";
    document.body.appendChild(anchor);
    anchor.click();
    
}

Upvotes: 1

Views: 3752

Answers (2)

Mari Magesh
Mari Magesh

Reputation: 44

download path should be in HTTP path then only it will work. local that will not work

Example

function file() {
const anchor = document.createElement("a");
anchor.href = "http://www.exampleApiPath.com/dingus.png";
anchor.download = "http://www.exampleApiPath.com/dingus.png";
document.body.appendChild(anchor);
anchor.click(); }

Upvotes: 0

Sandesh Damkondwar
Sandesh Damkondwar

Reputation: 446

Here it is, don't forget to remove the appended element.

function download(url) {
  const anchor = document.createElement('a')
  anchor.href = url
  anchor.download = url.split('/').pop()
  document.body.appendChild(anchor)
  anchor.click()
  document.body.removeChild(anchor)
}

Upvotes: 2

Related Questions