Here is the code.
On click of the link , the save as dialog 开发者_StackOverflowshould open
<a href="http://www.experts-exchange.com/xp/images/newNavLogo.png" target="_new">
<img src="http://www.experts-exchange.com/xp/images/newNavLogo.png" align="left" alt="" />
</a>
How can we achive this using jQuery, or javaScript?
If you are using PHP or any other platform you can always use the force download technique.
This might help:
<?php
$file = 'tag_cloud.gif';
if(!file){
// File doesn't exist, output error
die('file not found');
}else{
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: image/gif");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
}
?>
Call the above script as ajax in the click event of image.
Cheers
How about jDownload
?
Example usage is shown on the main page.
Edit: The link is now down and there are probably now better plugins for this.
Try http://jqueryfiledownload.apphb.com/
$("#img").click(function() {
document.execCommand('SaveAs','1','give img location here');
});
If that doesnt works use this jquery plugins for cross browser function "Cross-browser designMode"
http://plugins.jquery.com/project/designMode
Unfortunately, it works only with IE but not with Firefox.
</head>
<script>
function saveImageAs (imgOrURL) {
if (typeof imgOrURL == 'object')
imgOrURL = imgOrURL.src;
window.win = open (imgOrURL);
setTimeout('win.document.execCommand("SaveAs")', 500);
}
</script>
<body>
<A HREF="javascript: void 0"
ONCLICK="saveImageAs(document.anImage); return false"
>save image</A>
<IMG NAME="anImage" SRC="../apache_pb2.gif">
</body>
Try this
html:
<img src="http://www.experts-exchange.com/xp/images/newNavLogo.png" align="left" alt="" />
script:
$('img').each(function(){
$(this).wrap('<a href="'+this.src+'?download=true" target="_blank"/>');
});
most important you need to specify this on server side to send file with disposition attachment when ?downlaod=true was added
function dl(obj){
window.location = obj.src;
}
<br/>
..........
<br/>
<img src="http://www.experts-exchange.com/xp/images/newNavLogo.png" align="left" alt="" onClick="dl(this);"/>
<br/>
newer browsers will stick to the old page if a download redirect is made.
精彩评论