Search code examples
javascripthtmlpng

Javascript: "Save" a .PNG from an url


If the user clicks Accept in the following confirm box, a .png pre-defined file should be downloaded.

<script>
if(confirm('Press accept to download the .png')){ 
 //code to download the .png
}
</script>

Solution

  • Your problem is twofold...

    1. Download an image instead of displaying it.

    This is done with the download attribute...

    <a id="abc" href="some URL" download="some URL">Download Image</a>
    
    1. Link the DL with a confirm msg box...

    Putting it all together...

    <a id="abc" href="https://ibm.box.com/shared/static/tpnmvjclp166xbtlqpx712d2qzlvpity.png" download="https://ibm.box.com/shared/static/tpnmvjclp166xbtlqpx712d2qzlvpity.png" style="visibility:hidden;">Download Image</a>
    
    
    
    <body onload="if(confirm('Press accept to download the .png')){abc.click();}">
    

    NB: I'm hiding the anchor link from view with style="visibility:hidden;"