Skip to content

How to: Use file`s MD5 as filename

nofxx edited this page Sep 28, 2011 · 9 revisions

Inside your uploader class:

` def md5 chunk = model.#your upload_field - need to make smarter... @md5 ||= Digest::MD5.hexdigest(chunk.read) 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 :md5, :unique => true

before_save :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.

Clone this wiki locally