【问题标题】:how to make a button download a python file in html?如何使按钮下载html中的python文件?
【发布时间】: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


【解决方案1】:

您可以将其用于按钮

<form method="get" action="client.py">
   <button type="submit">Download!</button>
</form>

【讨论】:

  • 嗨,该代码仍会在新选项卡中打开 python 文件,并且只是在屏幕上显示它的代码...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-16
  • 1970-01-01
  • 2017-03-05
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
相关资源
最近更新 更多