Ruby file.original_filename 上传文件,文件名中文乱码怎么解决的啊

hyy044101331 · 2012年05月19日 · 最后由 woaigithub 回复于 2012年11月13日 · 14516 次阅读

aastring = "public/images/"+Time.now.strftime("%y-%m-%d")+(file.original_filename) File.open(aastring,"wb+") do |f| f.write(file.read) render(:text=>"afterupload :"+aastring+"上传成功!!!") end

加入这么一行就好了
CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:].-+]/

#1 楼 @liuhui998 这个正则没看懂...

@fsword

https://github.com/jnicklas/carrierwave

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 '-+_.' 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.

With Ruby 1.9 and higher you can simply write (as it has Oniguruma built-in):

CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:].-+]/

With Ruby 1.8 you have to manually specify all character ranges. For example, for files which may contain Russian letters:

CarrierWave::SanitizedFile.sanitize_regexp = /[^a-zA-Zа-яА-ЯёЁ0-9.-+_]/u

Also make sure that allowing non-latin characters won't cause a compatibility issue with a third-party plugins or client-side software.

补充下官方更新过的代码:

CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:].-+]/

最好是不要用用户的原始文件名来存储,有风险

#4 楼 @frankel #5 楼 @huacnlee

empty range in char class

#3 楼 @liuhui998 你肿么知道人家用了上传插件呢?

原始名称只是用来显示,网站自定义名称用来存储,然后配对使用。 其中一个问题就是原始文件名容易重复,那就不好办了。 还有其他的,请补充!

hyy044101331 关闭了讨论。 08月25日 15:53
需要 登录 后方可回复, 如果你还没有账号请 注册新账号