среда, 16 октября 2013 г.

Carrierwave and russian file names

When you upload a file with name like "картинка.jpg" you get someting like: "_______.jpg"
Oh no!

Let's use some source digging:

carrierwave/sanitized_file.rb
module CarrierWave
  class SanitizedFile
    attr_accessor :file
    class << self
      attr_writer :sanitize_regexp
      def sanitize_regexp
        @sanitize_regexp ||= /[^a-zA-Z0-9\.\-\+_]/
      end
    end
...
Redefine value of this attribute:
CarrierWave::SanitizedFile.sanitize_regexp = /[^a-zA-Zа-яА-ЯёЁ0-9\.\_\-\+\s\:]/
(thanks koHkB|/|cTadop)

 And put this code on the top of uploader file or in carrierwave initializer (if you want to use it in all your uploaders).

For russian filename basenames displayed like this:  %D0%BA%D0%B0%D1%80%D1%82%D0%B8%D0%BD%D0%BA%D0%B0.jpg" use URI.decode(string):
irb> URI.decode( "%D0%BA%D0%B0%D1%80%D1%82%D0%B8%D0%BD%D0%BA%D0%B0.jpg")
=> "картинка.jpg"

To read:
http://torubyonrails.blogspot.com/2013/05/carrierwave.html
carrierwave gem
URI::Escape

Комментариев нет:

Отправить комментарий