Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

python - How to change downloading name in flask?

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:

return send_file(os.path.join(filepath, filename))

That line returns the file which has filename like download without any format or something like that. Filename which has been downloaded is always the same and doesn't depend on real name of file. Real name of file is table.csv. How can I return the file with correct filename ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to set a Content-Disposition: attachment; filename=.... HTTP header for the browser to use the correct filename.

You can have send_file() set this header for you by setting the as_attachment=True argument. The filename is then taken from the file object you passed in. Use the attachment_filename argument to explicitly set a different filename:

return send_file(os.path.join(filepath, filename), as_attachment=True)

From the flask.send_file documentation:

  • as_attachment – set to True if you want to send this file with a Content-Disposition: attachment header.
  • attachment_filename – the filename for the attachment if it differs from the file’s filename.

You may want to use the flask.send_from_directory() function instead. That function first ensures that the filename exists (raising a NotFound if not), and ensures that the filename doesn't contain any .. relative elements that might be used to 'escape' the directory. Use this for all filenames taken from untrusted sources:

return send_from_directory(filepath, filename, as_attachment=True)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...