[英]how to download a file on disk with specific location using javascript or jquery?
我想使用javascript或jquery自动下载文件,以下是我正在使用的代码,但是该代码在浏览器的新选项卡中打开文件而不是在磁盘中下载。
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');
使用XMLHttpRequest()
从服务器请求文件作为Blob
,利用URL.createObjectURL()
<a>
与元素download
属性和href
属性设置为Blob URL
,然后调用.click()
上<a>
元素。
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();
尝试以下方法:
当ajax完成下载属性后,创建一个隐藏链接,触发该链接上的click事件
$('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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.