views:

272

answers:

2

Is there anyway to throw a validation error if a user tries to upload the same photo twice to a Rails app using Paperclip? Paperclip doesn't seem to offer this functionality...

I'm using Rails 2.3.5 and Paperclip (obviously).


SOLUTION: (or one of them, at least)

Using Beerlington's suggestion, I decided to go with an MD5 Checksum comparison:

class Photo < ActiveRecord::Base
  #...
  has_attached_file :image #, ...

  before_validation_on_create :generate_md5_checksum
  validate :unique_photo
  #...

  def generate_md5_checksum
    self.md5_checksum = Digest::MD5.hexdigest(image.to_file.read)
  end

  def unique_photo
    photo_digest = self.md5_checksum
    errors.add_to_base "You have already uploaded that file!" unless User.find(self.user_id).photos.find_by_md5_checksum(photo_digest).nil?
  end

  # ...
end

Then I just added a column to my photos table called md5_checksum, and voila! Now my app throws a validation error if you try to upload the same photo!

No idea how efficient/inefficient this is, so refactoring's welcome!

Thanks!

+1  A: 

As Stephen indicated, your biggest issue is how to determine if a file is a duplicate, and there is no clear answer for this.

If these are photos taken with a digital camera, you would want to compare the EXIF data. If the EXIF data matches then the photo is most likely a duplicate. If it is a duplicate then you can inform the user of this. You'll have to accept the upload initially though so that you examine the EXIF data.

I should mention that EXIFR is a nice ruby gem for examining the EXIF data.

sosborn
+4  A: 

What about doing an MD5 on the image file? If it is the exact same file, the MD5 hash will be the same for both images.

Beerlington
This works like a charm! Thanks; didn't think of this!
neezer