flask secure_filename无法获取中文
因为该方法采用ascii与正则匹配字母和数字,所以无法匹配中文等其他字符
所以需要修改源码。找到Lib\site-packages\werkzeug\utils的secure_filename方法
初始代码:
_filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9_.-]")#原始正则
if isinstance(filename, text_type): from unicodedata import normalize filename = normalize("NFKD", filename).encode("ascii", "ignore") if not PY2: filename = filename.decode("ascii") for sep in os.path.sep, os.path.altsep: if sep: filename = filename.replace(sep, " ") filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip( "._" )
改后的代码:
if isinstance(filename, text_type): from unicodedata import normalize filename = normalize("NFKD", filename).encode("utf-8", "ignore") if not PY2: filename = filename.decode("utf-8") for sep in os.path.sep, os.path.altsep: if sep: filename = filename.replace(sep, " ") _filename_ascii_add_strip_re = re.compile(r'[^A-Za-z0-9_\u4E00-\u9FBF.-]')#新的正则 filename = str(_filename_ascii_add_strip_re.sub("", "_".join(filename.split()))).strip( "._" )