[英]how to download a file on disk with specific location using javascript or jquery?
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. 我想使用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');
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. 使用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();
try the following: 尝试以下方法:
Create a hidden link when the ajax is complete with a attribute of download,trigger a click event on that link 当ajax完成下载属性后,创建一个隐藏链接,触发该链接上的click事件
$('body').append('<a class="hidden-ajax" download href="'+url+'"></a>')
$('.hidden-ajax').trigger('click');
JS JS
function(url){
window.href(url);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.