admin管理员组文章数量:1323029
I am trying to automatically download a file using javascript by creating a link and the clicking it. That works but using the download attribute, to specify the name the file will have, does not work.
Im using the code below
var a = document.createElement("a")
a.download = "hellooo.png"
a.href = ".png";
a.click();
Is there a way to make this work?
I am trying to automatically download a file using javascript by creating a link and the clicking it. That works but using the download attribute, to specify the name the file will have, does not work.
Im using the code below
var a = document.createElement("a")
a.download = "hellooo.png"
a.href = "http://icons.iconarchive./icons/yellowicon/game-stars/256/Mario-icon.png";
a.click();
Is there a way to make this work?
Share Improve this question asked Oct 13, 2014 at 10:03 CalthabisCalthabis 811 gold badge2 silver badges6 bronze badges 4- yes it's right w3schools./tags/att_a_download.asp – Mohamad Shiralizadeh Commented Oct 13, 2014 at 10:05
- In which browser you are trying to do this? – abhi Commented Oct 13, 2014 at 10:12
- I guess he mean IE/Safari because in Chrome/FF it works fine – A1rPun Commented Oct 13, 2014 at 10:39
-
2
Try setting
location.href
instead of faking a click. If the server response includes aContent-Disposition
header, it will be handled correctly as a download. The name will also be taken from the server response. – user663031 Commented Oct 13, 2014 at 12:22
1 Answer
Reset to default 4Here is my code using XMLHttpRequest ,tested in IE10+ , firefox ,and Chrome
function download(url, fileName) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onprogress = function(event) {
if (event.lengthComputable) {
var percentComplete = (event.loaded / event.total)*100;
//yourShowProgressFunction(percentComplete);
}
};
xhr.onload = function(event) {
if (this.status == 200) {
_saveBlob(this.response, fileName);
}
else {
//yourErrorFunction()
}
};
xhr.onerror = function(event){
//yourErrorFunction()
};
xhr.send();
}
function _saveBlob(response, fileName) {
if(navigator.msSaveBlob){
//OK for IE10+
navigator.msSaveBlob(response, fileName);
}
else{
_html5Saver(response, fileName);
}
}
function _html5Saver(blob , fileName) {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
document.body.removeChild(a);
}
本文标签: htmlDownload fileurl using JavascriptStack Overflow
版权声明:本文标题:html - Download fileurl using Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742110868a2421249.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论