【问题标题】:Download a file when button is pressed on web application?在Web应用程序上按下按钮时下载文件?
【发布时间】:2019-04-09 04:04:17
【问题描述】:

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

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

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>

【问题讨论】:

  • 请分享您的代码以展示您的尝试,我们也可以理解问题并尝试提供帮助。谢谢
  • 添加了简化版的代码。
  • 当我点击这个按钮时, .txt 文件没有保存到 /downloads,也没有提示将其保存到某个位置。当我“在新选项卡中打开链接”时,新选项卡显示“关于:空白”页面。我正在使用 Chrome 70.

标签: javascript python flask


【解决方案1】:

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

<?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);

?>

【讨论】:

    【解决方案2】:

    您可以使表单重定向到不同的烧瓶 url 并从烧瓶返回下载。

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

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2021-06-15
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多