Renaming uploaded files with Carrierwave

waving picture waving · Dec 14, 2010 · Viewed 23.7k times · Source

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 is a method I think I should be using

def filename
   "something.jpg" if original_filename
   basename = "what"+orginal_filename if original_filename, works
   basename = (0...8).map{65.+(rand(25)).chr}.join if original_filename  # will create a random name for each version, e.g. the orginal, the thumb, and the filename in the db, useless
 end

I can't seem to access items like 'extension' or 'content_type' in sanitized_file.rb, so this is a bit beyond my current skill level right now.

Any suggestions or exercises for doing this, i.e. generate filename for an uploaded file that works as well as the carrierwave default (do nothing, but does carry on to each version)? Seems like it should be simple enough but I've stumbled over this.

Answer

Jack Chu picture Jack Chu · May 3, 2011

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.