0

I'm trying to download an image using the download attribute on an <a> tag. Its href value is updated when it is clicked.

function Download_Image(element) {
  var mydiv = $("#imageDiv");
  var Image = mydiv[0].children;
  
  mydiv.download = Image[0].src;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="imageDiv">
  <img
    width="200"
    height="140"
    src="https://2.bp.blogspot.com/-pjQRansD-ig/XAUEH2oe8tI/AAAAAAAAHwE/BgZOyaGnQLYhH2Zjxx86BRvyOs8o9yGjgCLcBGAs/s200/16e3d864-8fb8-4f43-b91e-cc97a75c602f.jpg" />
</div>

<a href="#" onclick="Download_Image(this)" download>Click here to download image</a>

However, when I click the link, it downloads the whole HTML page instead of the image.

Danziger
  • 19,628
  • 4
  • 53
  • 83

1 Answers1

0

You need to change the href attribute of the <a> element, not the download attribute of the <div>.

Anyway, the download attribute is not supported in all browsers and might not work in some others if the Content-Disposition: attachment header is not set.

For example, if we use an image from Instagram with the following code, it will only work if you append ?dl=1 at the end of the URL:

const links = document.getElementById('links');
const image = document.getElementById('image');

links.onclick = (e) => {
  const link = e.target;
  
  if (link.tagName !== 'A') {
    return;
  }
    
  link.href = `${ image.src }${ link.innerText.includes('WITHOUT') ? '' : '?dl=1' }`;
}
body {
  height: 100vh;
  margin: 0;
  font-family: monospace;
  display: flex;
  align-items: center;
}

#image {
  margin: 8px;
  height: calc(100vh - 16px);
}

#links {
  display: flex;
  flex-direction: column;
}

#links > a {
  display: block;
  padding: 8px;
  line-height: 14px;
  margin: 4px 0;
  color: black;
  text-decoration: none;
  border: 3px solid black;
  border-radius: 2px;
}

#links > a:hover {
  background: yellow;
}
<img id="image" src="https://scontent-mad1-1.cdninstagram.com/vp/e96d73e7938825335c235baedb51e91a/5CAAC2D4/t51.2885-15/e35/46060357_1380937935382732_6380498939567322752_n.jpg" />

<div id="links">
  <a href="#" download> WITHOUT HEADER</a>
  <a href="#" download> WITH HEADER</a>
</div>

You could take a look at a library called download.js.

Danziger
  • 19,628
  • 4
  • 53
  • 83