Skip to content

How to: Use file`s MD5 as filename

Wang Hailong edited this page Dec 3, 2016 · 9 revisions

Inside your uploader class:

  def md5
    @md5 ||= Digest::MD5.hexdigest model.send(mounted_as).read.to_s
  end

  def filename
    @name ||= "#{md5}#{File.extname(super)}" if super
  end

Optionally, save the md5 in the DB too. Mongoid example:

class Asset
  include Mongoid::Document
  ...
  field :md5
  mount_uploader :data, AssetUploader
  validates_uniqueness_of :md5

  before_validation :update_data_attributes

  private

  def update_data_attributes
    if data.present? && data_changed?
      self.md5  = data.md5
    end
  end

This is also good to ensure unique/remove duplicates. Just a note: Mongoid sets the slug in a before_save block, you might want to move it to validation to make this validation work.

Clone this wiki locally