Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Save Image Onclick

On my website I have a jQuery script that, if the download button is clicked it will open the image that you want in new window.

My question is, how can I make this script when you click the button the image will save automatically and not open in a new window.

My code :

<script type="text/javascript">
        $(document).ready(function (){
            $('#download-btn').click(function(){
                var size = $('#size').val();                
                window.open(size);
            });
        })
    </script>
like image 965
Bogdan Crișu Avatar asked Oct 15 '25 15:10

Bogdan Crișu


2 Answers

First I try jqueryfiledonwloader but not work on image file,after a some searching I found below solution,This work for me charmly,try this

 <script type="text/javascript">
        $(document).ready(function (){
            $('#download-btn').click(function(){
     var link = document.createElement('a');
                  link.href = '/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg';  // use realtive url 
                  link.download = 'MyToy.jpeg';
                  document.body.appendChild(link);
                  link.click();     
           });
        })
    </script>
like image 99
Yuseferi Avatar answered Oct 17 '25 04:10

Yuseferi


<button class="btn btn-success" style="width: 250px;" data-image="/media/result/online_resultjpg_Page68.jpg" data-exam="GMO" data-roll="110211" onclick="downloadCertificate(this);" >Download Certificate</button>

<script type="text/javascript">
function downloadCertificate(obj){
    var link = document.createElement('a');
    const image = $(obj).data("image");
    const img_ext = image.split(".");
    const ext = img_ext[img_ext.length - 1];
    link.href = image;
    link.download = $(obj).data("exam") + "_" + $(obj).data("roll") + ext;
    document.body.appendChild(link);
    link.click();
}
</script>
like image 21
vinod kumar Avatar answered Oct 17 '25 06:10

vinod kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!