Sending file to the user gives UnicodeEncodeError in Flask framework

我怕爱的太早我们不能终老 提交于 2019-12-12 19:02:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!