Download image on button click using jQuery

2020-05-27 09:32发布

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

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

2条回答
何必那么认真
2楼-- · 2020-05-27 09:38

save.php will return

"1|DOWNLOAD_NOS|FULL_PATH|FILE_NAME" Or you may use 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);
    }
  });		
});	

查看更多
▲ chillily
3楼-- · 2020-05-27 09:55

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

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

FIDDLE

查看更多
登录 后发表回答