1. 程式人生 > >Flask檔案下載send_from_directory中文報錯處理

Flask檔案下載send_from_directory中文報錯處理

之前因為flask_restful接受中文引數有問題改了系統預設編碼

sys.setdefaultencoding('utf8')

本來以為之後就沒有中文問題了,沒想到檔案下載send_from_directory有個坑,執行下面程式碼報錯

return send_from_directory(dirpath, filename, as_attachment=True)

TypeError: must be unicode, not str

看網上說用下面程式碼,使用make_response可以處理中文問題,結果還是沒用

response = make_response(send_from_directory(directory, filename, as_attachment=True))
    response.headers["Content-Disposition"] = "attachment; filename={}".format(filename.encode().decode('latin-1'))

細看報錯過程,是send_from_directory方法,make_response還沒執行呼叫呢。考慮編碼問題直接出在filename上,因此嘗試如下程式碼,驗證沒有問題

send_from_directory(dirpath, filename.encode('utf-8').decode('utf-8'), as_attachment=True)