【发布时间】:2021-06-01 08:55:07
【问题描述】:
我尝试了几种方法,例如:
<button class="btn" type="submit" onclick="window.open('client.py')"><i class="fa fa-download"></i> Download</button>
或
<a href="/D:/Website/client.py" download>
python file
</a>
或
<a href="#" data-href='https://i.imgur.com/Mc12OXx.png' download="Image.jpg" onclick='forceDownload(this)'>Download Image</a>
js部分:
function forceDownload(link){
var url = link.getAttribute("data-href");
var fileName = link.getAttribute("download");
link.innerText = "Working...";
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
link.innerText="Download Image";
}
xhr.send();
}
但他们似乎都在新窗口中打开了 python 文件。而那个新的窗口/标签,只是在屏幕上显示文件的代码...... 但是,我希望将文件下载到计算机上,而不是在另一个窗口中打开! *我引用的最后一个代码根本不起作用,我不知道为什么,这也是一个不好的例子,因为我试图使用该代码来下载图片而不是 python 文件,但你明白了,此外,我很难理解代码,因为它使用 js,而 js 是一种我知之甚少的语言。 有人可以帮忙吗?
【问题讨论】:
-
在很多方面,这取决于浏览器。您的服务器还可以尝试发送有关该文件的更多信息,包括使用
Content-Disposition: attachment标头。 -
第一句话后我没听懂你在说什么
标签: javascript python html css