這個問題在這里已經有了答案:
我有一個匯出檔案路徑,它生成具有隨機名稱的 excel 檔案。然后它重定向到下載路由。fname 是檔案名。我已將其設為全球
@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"))
我有一條處理下載的路線。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)
在我的控制器中,我定義了上傳檔案夾,如下所示。
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
我的download.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>
uj5u.com熱心網友回復:
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)
uj5u.com熱心網友回復:
@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"))
在 download() 中檢索會話資料
@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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388400.html
