问题
I want to send the user a file when he clicks the appropriate button and I'm suing the following.
# Prepare selected file for download...
send_file( '/home/nikos/wsgi/static/files/' + filename )
But no matter what file the usser selects iam always receiving this response.
[Wed Sep 12 14:10:48.450211 2018] [wsgi:error] [pid 5172] [remote 46.103.174.201:14089] File "/home/nikos/wsgi/downloads.py", line 182, in file
[Wed Sep 12 14:10:48.450214 2018] [wsgi:error] [pid 5172] [remote 46.103.174.201:14089] send_file( '/home/nikos/wsgi/static/files/' + filename )
[Wed Sep 12 14:10:48.450219 2018] [wsgi:error] [pid 5172] [remote 46.103.174.201:14089] File "/usr/lib/python3.6/site-packages/flask/helpers.py", line 592, in send_file
[Wed Sep 12 14:10:48.450221 2018] [wsgi:error] [pid 5172] [remote 46.103.174.201:14089] file = open(filename, 'rb')
[Wed Sep 12 14:10:48.450237 2018] [wsgi:error] [pid 5172] [remote 46.103.174.201:14089] UnicodeEncodeError: 'ascii' codec can't encode characters in position 30-39: ordinal not in range(128)
How will I be able to send the selected file to the user?
回答1:
Try this.. Before sending the file do,
file_name.encode('utf-8')
So pass these additional parameters to send_file(), I've got these from this thread
attachment_filename=file_name.encode('utf-8'),as_attachment=True, conditional=True
So your send_file might look like this...
filepath = '/home/nikos/wsgi/static/files/' + filename
filepath = filepath.encode('utf-8')
send_file(attachment_filename=filepath,as_attachment=True, conditional=True)
Let me know if it worked so I can try further.
来源:https://stackoverflow.com/questions/52293860/sending-file-to-the-user-gives-unicodeencodeerror-in-flask-framework