Python Flask downloading a file returns 0 bytes

余生长醉 提交于 2019-12-19 06:57:56

问题


Here is the code my flask server is running:

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)

If the user goes to the site, it prints the files in the directory. However if you go to site:6969/filename it should download the file. However I am doing something wrong as the file size always 0 bytes and the downloaded file has no data in it. Any thoughts. I tried adding the content-length header and that didn't work. Don't know what else it could be.


回答1:


All that header does is tell the browser to treat the response data as a downloadable file with a certain name. It doesn't actually set any response data which is why it's blank.

You'd need to set the file contents on the response for it to work.

@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))

EDIT - Cleaned up code a little based on api docs




回答2:


As danny wrote, you don't provide any content in your response, that's why you get 0 bytes. There is however an easy function send_file in Flask to return file content:

from flask import send_file

@app.route("/<file_name>")
def getFile(file_name):
    return send_file(file_name, as_attachment=True)

Note that the file_name is relative to application root path (app.root_path) in this case.



来源:https://stackoverflow.com/questions/23354314/python-flask-downloading-a-file-returns-0-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!