Renaming uploaded files with Carrierwave

后端 未结 6 799
我寻月下人不归
我寻月下人不归 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:39

    Well, another problem with your random filename generator is that it's possible to have collisions isn't it? You could possibly generate a filename that was already generated. One way to go about it would be to somehow generate a hash based on unique properties of the image, like file path. An example, from the carrierwave group:

    def filename 
      if original_filename 
        @name ||= Digest::MD5.hexdigest(File.dirname(current_path))
        "#{@name}.#{file.extension}"
      end
    end
    

    This will create an MD5 hash based on the current path and then append the original file's extension to it.

    Edit: The carrierwave wiki added an entry with a few methods on how to create random and unique filenames for all versioned files.

提交回复
热议问题