Reputation: 380
Images are hosted outside the server and are downloaded only to the user (client side).
I have tried the HTML5 download tag, but it does not work very well with IE.
<div style="width:800px; height:457px; background-image:url('http://i.imgur.com/7fypLpI.jpg');"></div>
<a href="http://i.imgur.com/7fypLpI.jpg" download="http://i.imgur.com/7fypLpI.jpg">Download</a>
https://jsfiddle.net/eLpc8d7u/
How can I download the files for example with JavaScript for any browser?
I've seen this other question: IE download file
But I'm still confused to make a single script.
Upvotes: 1
Views: 3658
Reputation: 12022
For cross browser download including IE < 10 and IE >= 10, you can use the below library which will do task easy for you.
http://danml.com/js/download.js
GitHub Location: https://github.com/rndme/download
Sample code snippet for your case:
function downloadImage(event, url, fileName) {
event.preventDefault();
if(window.download && url) {
fileName = fileName || url.split('/').pop().split('?')[0];
var ajax = new XMLHttpRequest();
ajax.open( 'GET', url, true);
ajax.responseType = 'blob';
ajax.onload= function(e){
download(e.target.response, fileName, 'application/octet-stream');
};
setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
return ajax;
}
}
<script src="http://danml.com/js/download.js"></script>
<div style="width:800px; height:457px; background-image:url('http://i.imgur.com/7fypLpI.jpg');"></div>
<a href="http://i.imgur.com/7fypLpI.jpg" onclick="downloadImage(event, 'http://i.imgur.com/7fypLpI.jpg')">Download with default file name</a><br/>
<a href="http://i.imgur.com/7fypLpI.jpg" onclick="downloadImage(event, 'http://i.imgur.com/7fypLpI.jpg', 'testImage.jpg')">Download with custom file name</a>
Upvotes: 2