使用 jQuery 单击按钮下载图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18924238/
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-26 22:46:53  来源:igfitidea点击:

Download image on button click using jQuery

javascriptjqueryhtmlcss

提问by Anusha Honey

I have an image in my page. I want the image to be downloaded when I click on a button. How can I do this using jQuery or Javascript? Kindly provide me with a fiddle. FIDDLE

我的页面中有一张图片。我希望在单击按钮时下载图像。如何使用 jQuery 或 Javascript 执行此操作?请给我一个小提琴。小提琴

<div id="download">
    <img src="http://www.glamquotes.com/wp-content/uploads/2011/11/smile.jpg" id="image">
    <button id="dwnld"> Download image </button>
</div>

回答by adeneo

You can actually do this with the HTML5 downloadattribute, if older browsers are an issue, you should use the serverside for this, and set the appropriate headers etc.

您实际上可以使用 HTML5download属性执行此操作,如果较旧的浏览器有问题,您应该为此使用服务器端,并设置适当的标题等。

<a href="http://www.glamquotes.com/wp-content/uploads/2011/11/smile.jpg" download="smile.jpg">Download image</a>

FIDDLE

小提琴

回答by Monzur

save.php will return

save.php 将返回

"1|DOWNLOAD_NOS|FULL_PATH|FILE_NAME" Or you may use jSON

"1|DOWNLOAD_NOS|FULL_PATH|FILE_NAME" 或者你可以使用 jSON

$('#save_wall').click(function(e) {
  e.preventDefault();
  $.ajax({
    type: "POST",
    url:"save.php",
    data: "id=<?=$_GET['id'];?>",
    success: function (dataCheck) {
      var m=dataCheck.split("|");
      if(m[0] == '1') {
        alert("Thank You for your Download Picture\n\nShortly Picture Download will start...");
        $('#save_wall_count').html(m[1]);
        var a = document.createElement('a');
        a.href = m[2];
        a.download = m[3];
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
      if(m[0] == '0') 
        alert("Error: Error in Save Picture or Not Found...\n\n"+ dataCheck);
    }
  });  
});