jQuery 保存图像 Onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19753371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:33:46  来源:igfitidea点击:

jQuery Save Image Onclick

javascriptjqueryonclick

提问by Bogdan Cri?u

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.

在我的网站上,我有一个 jQuery 脚本,如果单击下载按钮,它将在新窗口中打开您想要的图像。

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>

回答by Yuseferi

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

首先我尝试jqueryfiledonwloader但不适用于图像文件,经过一番搜索后,我找到了以下解决方案,这对我来说很有用,试试这个

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

回答by Denis Hébert

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:

更高效,将直接在 HTML 中编码。因此,具有“按钮外观相似”样式的 Yusef 解决方案(请参阅如何使 html 链接看起来像按钮?例如),将简单地编码为:

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