Home > Software engineering >  How do I make a button that will download a file
How do I make a button that will download a file

Time:06-17

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

CodePudding user response:

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

CodePudding user response:

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(); }
  • Related