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.
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>
First I try jqueryfiledonwloader but not work on image file,after a some searching I found below solution,This work for me charmly,try this
<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>
<button class="btn btn-success" style="width: 250px;" data-image="/media/result/online_resultjpg_Page68.jpg" data-exam="GMO" data-roll="110211" onclick="downloadCertificate(this);" >Download Certificate</button> <script type="text/javascript"> function downloadCertificate(obj){ var link = document.createElement('a'); const image = $(obj).data("image"); const img_ext = image.split("."); const ext = img_ext[img_ext.length - 1]; link.href = image; link.download = $(obj).data("exam") + "_" + $(obj).data("roll") + ext; document.body.appendChild(link); link.click(); } </script>
Yuseferi script solution could be transformed into a simple anchor tag we put before the closing of the #download-btn
one:
<a href='/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg'
download='MyToy.jpeg'>MyToy.jpeg</a>
By the way, download
is a standard HTML5 anchor tag (MDN) attribute and, in script , it is flagged "experimental": maybe because of unwanted side effect. Still Yuseferi solution should be full proof.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.