我正在为我的一个模型使用标准的Django 1.7 FileField
。每当有人上传文件时,名称从看起来不错的东西(例如,“Some& File Name.xls”)变为看起来非常难看的东西(例如,“Some_File_Name.xls”)。这在存储类中完成,而存储类又调用django.utils.text.get_valid_filename
。请参阅以下代码:
def get_valid_filename(s):
"""
Returns the given string converted to a string that can be used for a clean
filename. Specifically, leading and trailing spaces are removed; other
spaces are converted to underscores; and anything that is not a unicode
alphanumeric, dash, underscore, or dot, is removed.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
"""
s = force_text(s).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
在我看来,大多数系统在这一点上都可以处理很多非单词字符。有关为什么以这种方式转义文件名的想法?