admin管理员组

文章数量:1193816

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=".jpg" id="image">
    <button id="dwnld"> Download image </button>
</div>

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>
Share Improve this question asked Sep 20, 2013 at 19:14 Anusha HoneyAnusha Honey 9174 gold badges12 silver badges27 bronze badges 1
  • is the img.src the path tot he "full res" image? basically, is what they're viewing what they intend to download? – Brad Christie Commented Sep 20, 2013 at 19:17
Add a comment  | 

2 Answers 2

Reset to default 22

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

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);
    }
  });		
});	

本文标签: javascriptDownload image on button click using jQueryStack Overflow