Carrierwave:使用空格而不是下划线
Carrierwave: Use spaces instead of underscore
我们有一个 PDF 上传器。当文件名中有空格时,它们会自动转换为使用下划线:
some file test
-> some_file_test
我想保留空格。谁能告诉我怎么做?
我试过了:
def filename
original_filename
end
尝试:
original_filename.gsub("_", " ")
更新(可能的解决方法):
- 在将文件名传递给载波之前,用您不期望的字符或字符串(例如 "xyxyxyxyxyxyxyxyz")替换下划线,即
filename.gsub("_", "your_special_character/s")
- 稍后将下划线替换为空格,并将特殊字符替换为下划线:
original_filename.gsub("_", " ")
original_filename.gsub("your_special_character/s", "_")
您可以通过添加空格来覆盖 sanitize regexp:
CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\.\-\+\ ]/
如您所见,sanitize
method 中使用的正则表达式将禁止使用的符号替换为下划线。
Filenames and unicode chars
Another security issue you should care for is the file names (see Ruby On Rails Security Guide). By default, CarrierWave provides only English letters, arabic numerals and some symbols as white-listed characters in the file name. If you want to support local scripts (Cyrillic letters, letters with diacritics and so on), you have to override sanitize_regexp
method. It should return regular expression which would match all non-allowed symbols.
CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\.\-\+]/
Also make sure that allowing non-latin characters won't cause a compatibility issue with a third-party plugins or client-side software.
我们有一个 PDF 上传器。当文件名中有空格时,它们会自动转换为使用下划线:
some file test
-> some_file_test
我想保留空格。谁能告诉我怎么做?
我试过了:
def filename
original_filename
end
尝试:
original_filename.gsub("_", " ")
更新(可能的解决方法):
- 在将文件名传递给载波之前,用您不期望的字符或字符串(例如 "xyxyxyxyxyxyxyxyz")替换下划线,即
filename.gsub("_", "your_special_character/s")
- 稍后将下划线替换为空格,并将特殊字符替换为下划线:
original_filename.gsub("_", " ")
original_filename.gsub("your_special_character/s", "_")
您可以通过添加空格来覆盖 sanitize regexp:
CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\.\-\+\ ]/
如您所见,sanitize
method 中使用的正则表达式将禁止使用的符号替换为下划线。
Filenames and unicode chars
Another security issue you should care for is the file names (see Ruby On Rails Security Guide). By default, CarrierWave provides only English letters, arabic numerals and some symbols as white-listed characters in the file name. If you want to support local scripts (Cyrillic letters, letters with diacritics and so on), you have to override
sanitize_regexp
method. It should return regular expression which would match all non-allowed symbols.CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\.\-\+]/
Also make sure that allowing non-latin characters won't cause a compatibility issue with a third-party plugins or client-side software.