简体   繁体   English

如何使用 send_from_directory 从 Flask 下载文件?

[英]How to download a file from Flask with send_from_directory?

Hi I am having trouble downloading a csv file in Flask which is stored in csv_files folder.嗨,我无法在 Flask 中下载 csv 文件,该文件存储在 csv_files 文件夹中。 The structure of the files is as below.文件的结构如下。 I am getting requested url is not found on server error.我收到请求 url 在服务器错误中找不到。 Please help I am a novice Flask user.请帮助我是新手 Flask 用户。

在此处输入图像描述

I have an export file route which generates the excel file with a random name.我有一个导出文件路径,它生成具有随机名称的 excel 文件。 It then redirects to download route.然后它重定向到下载路线。 fname is the name of the file. fname 是文件的名称。 I have made it as global我已经把它变成了全球性的

@app.route("/exportfile",methods=["GET","POST"])
def exportfile():


    if request.method=='GET':

        export_list=End_list.query.all()
        print(export_list)
        global fname
        fname = str(uuid.uuid4())

        outfile = open(f'./csv_files/{fname}.csv', 'w',newline='')
        outcsv = csv.writer(outfile)
        outcsv.writerow(["Sr Number","SK","Quantity","Length","ToolCode","Description"])
        for x in export_list:

             outcsv.writerow([x.srnuml,x.sk,x.quantity,x.length,x.toolcode,x.description.strip()])

        outfile.close()

        return redirect(url_for("download"))

I have a route handling the download.我有一条处理下载的路线。 There's a download button in the html which does a POST request. html 中有一个下载按钮,它执行 POST 请求。

@app.route("/download",methods=["GET","POST"])
def download():

    if request.method=="GET":
        return render_template("download.html")

    elif request.method=="POST":
        
        return send_from_directory(app.config['UPLOAD_FOLDER'], filename=fname, as_attachment=True, cache_timeout=0)

In my controllers, I have defined the upload folder as below.在我的控制器中,我定义了上传文件夹,如下所示。

import os

basedir = os.path.abspath(os.path.dirname(__file__))


class Config:
    DEBUG = False
    SQLITE_DB_DIR = None
    SQLALCHEMY_DATABASE_URI = None
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    UPLOAD_FOLDER = None

class LocalDevelopmentConfig(Config):
    SQLITE_DB_DIR = os.path.join(basedir)
    SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.join(SQLITE_DB_DIR, "toolcodes.sqlite3")
    UPLOAD_FOLDER = basedir+"/csv_files"
    DEBUG = True

My download.html is as below:我下载的.html如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

        Download will happen here
        <br><br>
        <form method="POST" action="/download">

            <input name="Download" type="submit" value="Download">

        </form>
        <br>
        <a href="{{url_for('dashboard')}}"> Go to dashboard</a>

</body>
</html>
from flask import send_file

@app.route('/download',methods=["GET","POST"])
def downloadFile(csvFileName): #In your case fname is your filename
    try:
       path = f'./csv_files/{csvFileName}'
       return send_file(path,mimetype='text/csv', attachment_filename=csvFileName, as_attachment=True)
    except Exception as e:
        return str(e)
@app.route("/exportfile",methods=["GET","POST"])
def exportfile():


    if request.method=='GET':

        export_list=End_list.query.all()
        print(export_list)
        global fname
        fname = str(uuid.uuid4())
        session['fname'] = fname # change here

        outfile = open(f'./csv_files/{fname}.csv', 'w',newline='')
        outcsv = csv.writer(outfile)
        outcsv.writerow(["Sr Number","SK","Quantity","Length","ToolCode","Description"])
        for x in export_list:

             outcsv.writerow([x.srnuml,x.sk,x.quantity,x.length,x.toolcode,x.description.strip()])

        outfile.close()

        return redirect(url_for("download"))

retrieve session data in download()在下载()中检索 session 数据

@app.route("/download",methods=["GET","POST"])
def download():


    if request.method=="GET":
        return render_template("download.html")

    elif request.method=="POST":
        if 'fname' in session:
            csvFileName = session['fname']
            return send_from_directory(app.config['UPLOAD_FOLDER'], filename=csvFileName , as_attachment=True, cache_timeout=0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM