Python file download Flask returns 0 bytes

Here is the code that runs my flask server:

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, he prints the files in the directory. However, if you go to the site: 6969 / filename, it must download the file. However, I am doing something wrong, since the file size is always 0 bytes, and the downloaded file does not contain data. Any thoughts. I tried to add a content length header, and that didn't work. I don’t know what else could be.

+6
source share
2 answers

Everything that this header does tells the browser to process the response data as a download file with a specific name. In fact, it does not specify any response data, so it is empty.

You will need to set the contents of the file in 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 - slightly cleared api docs based code

+6
source

As Danny wrote, you are not providing any content in your answer, so you get 0 bytes. However, there is an easy send_file function in Flask to return the contents of a file:

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

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

+10
source

All Articles