Renaming uploaded files with Carrierwave

后端 未结 6 801
我寻月下人不归
我寻月下人不归 2021-01-31 08:46

I\'m using Carrierwave to upload files, and I have it working.

My issue is attempting to change the name of the uploaded file.

In the generated uploader.rb there

6条回答
  •  走了就别回头了
    2021-01-31 09:25

    To have a real unique filename (not almost unique) I recommend to use the uuid gem.

    in Gemfile add:

    gem 'uuid'
    

    in file_uploader.rb:

    def filename
      if original_filename
        if model && model.read_attribute(mounted_as).present?
          model.read_attribute(mounted_as)
        else
          @name ||= "#{mounted_as}-#{uuid}.#{file.extension}"
        end
      end
    end
    
    protected
    
    def uuid
      UUID.state_file = false
      uuid = UUID.new
      uuid.generate
    end
    

提交回复
热议问题