Python Flask downloading a file returns 0 bytes

前端 未结 2 761
[愿得一人]
[愿得一人] 2021-01-12 23:50

Here is the code my flask server is running:

from flask import Flask, make_response
import os

app = Flask(__name__)

@app.route(\"/\")
def index():
                 


        
2条回答
  •  耶瑟儿~
    2021-01-13 00:21

    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("/")
    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

提交回复
热议问题