[英]Python Flask downloading a file returns 0 bytes
這是我的燒瓶服務器運行的代碼:
from flask import Flask, make_response
import os
app = Flask(__name__)
@app.route("/")
def index():
return str(os.listdir("."))
@app.route("/<file_name>")
def getFile(file_name):
response = make_response()
response.headers["Content-Disposition"] = ""\
"attachment; filename=%s" % file_name
return response
if __name__ == "__main__":
app.debug = True
app.run("0.0.0.0", port = 6969)
如果用戶訪問該站點,則會在目錄中打印文件。 但是,如果你去網站:6969 / filename它應該下載文件。 但是我做錯了,因為文件大小總是0字節,下載的文件中沒有數據。 有什么想法嗎。 我嘗試添加內容長度標頭,但沒有用。 不知道它還能是什么。
正如danny所寫,你沒有在你的回復中提供任何內容,這就是你獲得0字節的原因。 然而,在Flask中有一個簡單的函數send_file來返回文件內容:
from flask import send_file
@app.route("/<file_name>")
def getFile(file_name):
return send_file(file_name, as_attachment=True)
請注意,在這種情況下, file_name
與應用程序根路徑( app.root_path
)相關。
所有標題都是告訴瀏覽器將響應數據視為具有特定名稱的可下載文件。 它實際上並沒有設置任何響應數據,這就是為什么它是空白的。
您需要在響應上設置文件內容才能生效。
@app.route("/<file_name>")
def getFile(file_name):
headers = {"Content-Disposition": "attachment; filename=%s" % file_name}
with open(file_name, 'r') as f:
body = f.read()
return make_response((body, headers))
編輯 - 根據api文檔稍微清理一下代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.