jQuery Save Image Onclick

十年热恋 提交于 2019-12-07 16:39:05

问题


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>

回答1:


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>



回答2:


More efficient, would be coding directly in HTML. So Yusef solution, with a "Button Look Alike" Style (see How do I make an html link look like a button? for example), would simply be coded like this:

<a id='download-btn' href='/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg'
   download='MyToy.jpeg' class="button">Save as MyToy.jpeg</a>


来源:https://stackoverflow.com/questions/19753371/jquery-save-image-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!