CarrierWave: Create the same, unique filename for all versioned files

后端 未结 3 1163
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 11:46

Before I go into detail I\'ll get right to the point: has anyone figured out a way to get Carrierwave to save files with their names as a timestamp or any arbitrary string that

3条回答
  •  情歌与酒
    2021-02-02 12:05

    You can do something like this in your uploader file, and it will also work for versioned files (i.e. if you have one image and then create 3 other thumbnail versions of the same file, they will all have the same name, just with size info appended onto the name):

      # Set the filename for versioned files
      def filename
        random_token = Digest::SHA2.hexdigest("#{Time.now.utc}--#{model.id.to_s}").first(20)
        ivar = "@#{mounted_as}_secure_token"    
        token = model.instance_variable_get(ivar)
        token ||= model.instance_variable_set(ivar, random_token)
        "#{model.id}_#{token}.jpg" if original_filename
      end
    

    This will create a filename like this for example: 76_a9snx8b81js8kx81kx92.jpg where 76 is the model's id and the other bit is a random SHA hex.

提交回复
热议问题