Reputation: 121
I have on html page input type text. I want paste URL, on example http://www.quicksprout.com/images/foggygoldengatebridge.jpg in this text field and click button "download" and download this file to my computer. I want want to realize this with AJAX. Maybe do you know some AJAX plugins or code that could realize downloading file from HTTP URL?
Upvotes: 0
Views: 2851
Reputation: 2617
First MEthod
function SaveToDisk(fileURL, fileName) {
//alert("yes i m working");
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
Second MEthod
function downloadme(x,y){
myTempWindow = window.open(x,'','left=10000,screenX=10000');
myTempWindow.document.execCommand('SaveAs','null',y);
myTempWindow.close();
}
Upvotes: 2
Reputation: 51756
You don't need AJAX to do that, nor would you be able to because of CORS limitations. Instead try something like this.
HTML:
<input type="text" placeholder="URL" id="url"/>
<input type="text" placeholder="Filename" id="name"/>
<a id="download">Download Link</a>
JavaScript:
var url = document.getElementById('url'),
name = document.getElementById('name'),
a = document.getElementById('download');
a.addEventListener('click', function () {
this.setAttribute('src', url.value);
this.setAttribute('download', name.value);
});
Upvotes: 1