I have a small project which has to response some files. I know that using nginx
will be better decision but that files a really small.
Part of my program:
In my case, setting the as_attachment
and attachment_filename
did not work because the Content-Disposition: attachment
does not appear in the client-side copy of the response.
If you have Flask-CORS enabled, you can initialize it with expose_headers set to a custom header that specifies the filename (ex. "x-suggested-filename"). Then add that header to the response.
# In file where the Flask app instance is initialized
app = Flask(__name__)
CORS(app, expose_headers=["x-suggested-filename"])
# In file with the download endpoint
result = send_file("/full/path/to/some/file",
mimetype="text/plain", # use appropriate type based on file
as_attachment=True,
conditional=False)
result.headers["x-suggested-filename"] = "use_this_filename.txt"
return result
Then, in the client-side download code, you can inspect the response headers to get the filename from the same custom header:
# Using axios and FileSaver
let response = await axios.get(downloadUrl, downloadConfig);
let filename = response.headers["x-suggested-filename"];
FileSaver.saveAs(response.data, filename);