在Web应用程序上按下按钮时下载文件? [英] Download a file when button is pressed on web application?
问题描述
我正在使用python和Flask构建一个Web应用程序.我已经在Web应用程序上实现了一个按钮,该按钮在python后端中调用一个方法并生成一个.txt文件,该文件保存在当前目录(存储当前.html和.py文件的位置)中.一旦方法完成运行并生成.txt文件,我希望能够提示用户将.txt文件保存在本地计算机上(就像按另存为...时出现的Windows提示...").
I'm building a web app using python and Flask. I have implemented a button on the web app that calls a method in the python back-end and generates a .txt file which is saved in the current directory (where the current .html and .py files are stored). Once, the method finished running and the .txt file is generated, I want to be able to prompt the user to save the .txt file on the local computer (just like the windows prompt you get when you press "save as..." on a webpage).
这是网络应用程序的简化版本
Here is a simplified version of the web app
test.py
from flask import Flask, render_template, flash, request, redirect, url_for
import pandas as pd
# User Interface of the Web App
# App config.
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '123455677889900'
@app.route("/", methods=['GET', 'POST'])
def predict():
if 'submit_test' in request.form:
list = []
for i in range(0, 100):
list.append(i)
list_df = pd.DataFrame(list)
list_df.to_csv('test.txt', sep=',',index=False)
return render_template('test.html')
if __name__ == "__main__":
method_name = "main"
app.run()
test.html
test.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Model</title>
<link rel="stylesheet" media="screen" href ="static/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap-theme.min.css">
<meta name="viewport" content = "width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h1>Model</h1>
<br>
<form action="" method="post" role="form">
<div class="row">
<div class="col-12 col-md-6">
<button name="submit_test", type="submit" class="btn btn-success" id="submit_test">Submit</button>
</div>
</div>
</form>
<a href="directory\test.txt" download="test"><button type=button">My Button</button></a>
</div>
</body>
<br>
</html>
推荐答案
您可以将表单重定向到其他flask网址,然后从flask返回下载.
You can make the form redirect to a different flask url and return the download from flask.
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory=os.getcwd()+"/files", filename="filename.txt")
这篇关于在Web应用程序上按下按钮时下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!