i want to download a file automatically using javascript or jquery below is the code which i am using but that code open the file in new tab in browser not download in disk.
function SaveToDisk(fileUrl, fileName) {
var hyperlink = document.createElement('a');
hyperlink.href = fileUrl;
hyperlink.target = '_blank';
hyperlink.download = fileName || fileUrl;
(document.body || document.documentElement).appendChild(hyperlink);
hyperlink.onclick = function() {
(document.body || document.documentElement).removeChild(hyperlink);
};
var mouseEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
hyperlink.dispatchEvent(mouseEvent);
// NEVER use "revoeObjectURL" here
// you can use it inside "onclick" handler, though.
// (window.URL || window.webkitURL).revokeObjectURL(hyperlink.href);
// if you're writing cross-browser function:
if(!navigator.mozGetUserMedia) { // i.e. if it is NOT Firefox
window.URL.revokeObjectURL(hyperlink.href);
}
}
SaveToDisk('http://example.com/service/getUserImage/339/256', 'image.png');
Use XMLHttpRequest()
to request file from server as a Blob
, utilize URL.createObjectURL()
, <a>
element with download
attribute and href
attribute set to Blob URL
, then call .click()
on <a>
element.
var request = new XMLHttpRequest();
request.open("GET", "http://example.com/service/getUserImage/339/256");
request.responseType = "blob";
request.onload = function() {
var a = document.createElement("a");
a.href = URL.createObjectURL(this.response);
a.download = this.response.name;
document.body.appendChild(a);
a.click();
}
request.send();
try the following:
Create a hidden link when the ajax is complete with a attribute of download,trigger a click event on that link
$('body').append('<a class="hidden-ajax" download href="'+url+'"></a>')
$('.hidden-ajax').trigger('click');
JS
function(url){
window.href(url);
}
var count=0;
$('#testdownload').on('click', function(){
count++;
$('#log').append('<li>Click triggered ' + count + ' times</li>');
});
$('#testdownload').get(0).click();
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.