0

Hello I am trying to code an HTML button to download an image.

Here is the code I am using that seems like I am getting close but not quite there.

<a href="https://assets.giftcardsuite.com/valentinesday/Valentines-Day-Theme-1.png" download>
  <img src="https://assets.giftcardsuite.com/valentinesday/Valentines-Day-Theme-1.png" class="img-responsive" alt="happy-valentines-day"> Click Here To Download
</a>

Here is a screenshot of what it looks like when I download it: https://snag.gy/tTC2ER.jpg

  • Why are you not using the ` – Keka Bron Jan 27 '19 at 21:29
  • Possible duplicate of [href image link download on click](https://stackoverflow.com/questions/2408146/href-image-link-download-on-click) – rsm Jan 27 '19 at 21:33

3 Answers3

0
  1. You can check this response: href image link download on click

  2. Also this answer using Jquery Download Plugin

  3. Try this script:

//https://stackoverflow.com/a/50042812/10849656

function forceDownload(link){
    var url = link.getAttribute("data-href");
    var fileName = link.getAttribute("download");
    link.innerText = "...";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = function(){
        var urlCreator = window.URL || window.webkitURL;
        var imageUrl = urlCreator.createObjectURL(this.response);
        var tag = document.createElement('a');
        tag.href = imageUrl;
        tag.download = fileName;
        document.body.appendChild(tag);
        tag.click();
        document.body.removeChild(tag);
        link.innerText="Download";
    }
    xhr.send();
}
<a href="#" data-href='https://i.imgur.com/mdYoHMD.jpg' download="Image.jpg" onclick='forceDownload(this)'>Download Image</a>
sanyaissues
  • 161
  • 2
  • 5
0

I think your code is disarranged

Try this:

<a href="https://assets.giftcardsuite.com/valentinesday/Valentines-Day-Theme-1.png" download>Click here</a> to download
0

When I download something I usually use my download function below. I don't need to remove from DOM because it never gets placed in the DOM.

Javascript

function download(data, name) {
      var blob = new Blob([data], {type: 'application/octect-stream'});
      var bloburl = URL.createObjectURL(blob);
      var a = document.createElement('a');
      a.href = bloburl;
      a.download = name;
      a.click();
      URL.revokeObjectURL(blob);
}
myjobistobehappy
  • 736
  • 5
  • 16