[英]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.