您尝试解决该任务将是可取且有用的。该平台不是一项服务,您可以让其他人为您编程,而是当您在尝试中遇到问题时提供帮助。
然而,在下面我的例子中是例外的。
请求的文件在服务器上使用variable rule 标识并通过send_from_directory 发送。
相应的文本文档应位于项目的“文件”文件夹中。在示例中,根据您的规范,需要一个名为“local_filename.txt”的文档。
from flask import Flask, render_template, send_from_directory
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/download/<path:filename>')
def download(filename):
return send_from_directory(
'files',
filename,
as_attachment=True
)
为了对按钮的点击做出反应,请求所有必要的按钮并为它们注册一个event listener。点一下,请求按钮的data attribute,生成需要的url。这样做时,考虑到这是一个有效的表格。
方法类型 GET 的请求是由异步 Javascript (AJAX) 使用 fetch 命令发出的。发送的数据以Blob 的形式接收。内容被提取并显示。没有考虑 HTML 特定的字符。
名为“index.html”的模板应位于项目的“templates”文件夹中。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button data-source="local_filename.txt">Retrieve</button>
<output id="result"></output>
<script type="text/javascript">
(function(){
let elems = document.querySelectorAll("button[data-source]")
elems.forEach(elem => {
elem.addEventListener('click', event => {
const url = `/download/${encodeURIComponent(elem.dataset.source)}`;
fetch(url)
.then(resp => resp.blob())
.then(blob => {
blob.text().then(text => {
document.getElementById("result").innerHTML = text;
});
})
.catch(err => console.error("Error", err));
});
});
})();
</script>
</body>
</html>
如果此示例满足您的要求,我会很高兴,并会要求您在未来遵守此服务的规则和程序。
在实施您的项目时获得乐趣并取得成功。