在Web应用程序上按下按钮时下载文件?

时间:2018-11-05 18:54:14

标签: javascript python flask

我正在使用python和Flask构建一个Web应用程序。我已经在Web应用程序上实现了一个按钮,该按钮在python后端中调用一个方法并生成一个.txt文件,该文件保存在当前目录(存储当前.html和.py文件的位置)中。一旦该方法运行完毕并生成.txt文件,我希望能够提示用户将.txt文件保存在本地计算机上(就像按Windows时按下“另存为...时得到的提示... ”)。

这是网络应用程序的简化版本

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

<!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>

2 个答案:

答案 0 :(得分:1)

您可以将表单重定向到其他flask网址,然后从flask返回下载。

@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    return send_from_directory(directory=os.getcwd()+"/files", filename="filename.txt")

答案 1 :(得分:0)

这至少应该为您指明正确的方向:

<?php

//set path to file
$filePath = "path/to/file.txt";

//set file name (basename() returns the actual filename)
$fileName = basename($filePath);

//set content type
header('Content-Type: text/plain');

//set content disposition to 'attachment' to prompt download
header('Content-Disposition: attachment; filename="' . $fileName . '"');

//read the file and write its contents to the output buffer
readfile($filePath);

?>
相关问题