Paperclip renaming files after they're saved

前端 未结 9 1480
情书的邮戳
情书的邮戳 2020-12-07 23:34

How do I rename a file after is has been uploaded and saved? My problem is that I need to parse information about the files automatically in order to come up with the file

9条回答
  •  被撕碎了的回忆
    2020-12-08 00:15

    Another option is set to default, work for all upload.

    This example change name file to 'name default' for web, example: test áé.jpg to test_ae.jpg

    helper/application_helper.rb

    def sanitize_filename(filename)
        fn = filename.split /(?<=.)\.(?=[^.])(?!.*\.[^.])/m
        fn[0] = fn[0].parameterize
        return fn.join '.'
    end
    

    Create config/initializers/paperclip_defaults.rb

    include ApplicationHelper
    
    Paperclip::Attachment.default_options.update({
        :path => ":rails_root/public/system/:class/:attachment/:id/:style/:parameterize_file_name",
        :url => "/system/:class/:attachment/:id/:style/:parameterize_file_name",
    })
    
    Paperclip.interpolates :parameterize_file_name do |attachment, style|
        sanitize_filename(attachment.original_filename)
    end
    

    Need restart, after put this code

提交回复
热议问题