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?
2 Answers
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();
}
6 Comments
Patrick Roberts
Browsers are usually sophisticated enough to block anchor tags clicked with generated mouse events, be aware of this limitation.
mvoron
first method works, thanks, but how in this code I can change directory to save file?
Bugfixer
@mvoron - This is force downloading buddy.
Johnny
thanks for the first method. it saves the files as "unknown" I changed it to fileURL it saved it as "http---localhost-ieltsmaster-gtreading-workbook-Activity_3_1.pdf" Any idea how to fix it?
|
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);
});