Sending file to the user gives UnicodeEncodeError in Flask framework
> On Wed, 12 Sep 2018 06:57:36 -0700, ????? ?????? wrote:
>> 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
>> [Wed Sep 12 14:10:48.450211 2018] [wsgi:error] [pid 5172] [remote
>> 18.104.22.168:14089] File "/home/nikos/wsgi/downloads.py", line
>> 182, in file [Wed Sep 12 14:10:48.450214 2018] [wsgi:error] [pid
>> 5172] [remote 22.214.171.124:14089] send_file(
>> '/home/nikos/wsgi/static/files/' + filename )
>> [Wed Sep 12 14:10:48.450219 2018] [wsgi:error] [pid 5172] [remote
>> 126.96.36.199: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 188.8.131.52:14089] file = open(filename, 'rb')
>> [Wed Sep 12 14:10:48.450237 2018] [wsgi:error] [pid 5172] [remote
>> 184.108.40.206:14089] UnicodeEncodeError: 'ascii' codec can't encode
>> characters in position 30-39: ordinal not in range(128)
The "UnicodeEncodeError" indicates that Python tries to convert
(= "encode") a unicode string into bytes and the corresponding encoding
is unable to do so.
It is quite natural, that the "send_file" wants to transfer bytes.
It is not natural that in between it has to handle unicode.
The "open(filename, 'rb')" should open the file in binary (= bytes) mode;
subsequent reads should return bytes.
But, potentially, the "open(filename, 'rb')", itself, raises
the "UnicodeEncodeError". Is it possible that your "filename"
contains special characters? In this case, you may need to
encode (the complete!) filename yourself with an encoding
appropriate for your file system (likely "utf-8") before you
pass it to "send_file".