1

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();
    
}
ßamuel
  • 35
  • 7
  • 1
    Before download file you should point the file. Such an request from api or for local file you can use File API of JavaScript. – Emran Jun 17 '22 at 04:58
  • 1
    According to [this post](https://stackoverflow.com/a/17527821/2610061) cross origin downloads with the `download` attribute are no longer supported. – Carsten Massmann Jun 17 '22 at 05:10

2 Answers2

2

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

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