4

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>
0

3 Answers 3

8

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Hi sir how about javascript button onclick get elementbyid file upload to project directory I cant find a certain script for that please help stackoverflow.com/questions/63218454/…
1

<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>

Comments

0

Yuseferi script solution could be transformed into a simple anchor tag we put before the closing of the #download-btn one:

<a href='/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg'
   download='MyToy.jpeg'>MyToy.jpeg</a>

By the way, download is a standard HTML5 anchor tag (MDN) attribute and, in script, it is flagged "experimental": maybe because of unwanted side effect. Still Yuseferi solution should be full proof.

2 Comments

The anchor tag does not have an attribute download. dev.w3.org/html5/html-author
@m02ph3u5, download attribute is part of the newest HTML5 anchor tag (MDN) and it is still experimental as an HTMLAnchorElement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.