-1

I want to download a picture as soon as I click on it. The picture itself is SVG but I have an URL for a PNG image. I checked and the content disposition is attachment, and yes when I copy the URL directly a download immediately starts.

I am using Bootstrap 4

The function

function downloadPNGImage(linkElement) {
    var myDiv = document.getElementById('download-area');
    var myImage = myDiv.children[0];
    let downloadLink = myImage.src + "&format=png";
    linkElement.setAttribute('download', downloadLink);
    linkElement.href = downloadLink;
}

And the image itself is:

            <div class="col-lg-5 order-first order-md-last img-fluid" id="download-area">
                <img src="https://bananomonkeys.herokuapp.com/image?address=ban_1ttyqinz739g88tteqzyg3hwahg9oxbks8amsywqmim7j4afih7n9d1ssqjf&bg=t"
                    class="loaded" id="generated-monKey" alt="" href="#" onclick="downloadPNGImage(this)" download>
            </div>

So when I add "&format=png" this URL is no longer an inline SVG, it is an attached PNG that I would like to download, but for some reason, it doesn't work.

Rajib karmaker
  • 466
  • 1
  • 5
  • 16
Randomizer
  • 475
  • 7
  • 19

4 Answers4

1

modify the function a bit:

function downloadPNGImage(linkElement) {
    var myDiv = document.getElementById('download-area');
    var myImage = myDiv.children[0];
    let downloadLink = myImage.src + "&format=png";
    linkElement.setAttribute('download', downloadLink);
    linkElement.href = downloadLink;
    linkElement.click();
}

modify the onclick handler:

onclick="downloadPNGImage(document.createElement('a'))"
ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22
0

The download attribute won't work on an <img> tag you would be better wrapping your image in an <a> tag and adding the download attribute to that instead. In your javascript you are adding a .href to an img tag which again won't do anything.

Aaron McGuire
  • 1,217
  • 10
  • 14
0

I would open new window with generated link. So the code would look like this:

function downloadPNGImage(linkElement) {
    var myDiv = document.getElementById('download-area');
    var myImage = myDiv.children[0];
    let downloadLink = myImage.src + "&format=png";
    window.open(downloadLink);
}
Maciej Kasprzak
  • 929
  • 6
  • 17
0

Why do you want to use JS?

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_a_download

or if you need cross origin:

https://stackoverflow.com/a/49886131/9590657

This question is close to your question: Force browser to download image files on click

Terus
  • 127
  • 1
  • 8