Rails:使用回形针防止重复上传照片? [英] Rails: Preventing Duplicate Photo Uploads with Paperclip?
问题描述
如果用户尝试使用 Paperclip 将同一张照片两次上传到 Rails 应用程序,是否会引发验证错误?Paperclip 似乎不提供此功能...
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...
我正在使用 Rails 2.3.5 和 Paperclip(显然).
I'm using Rails 2.3.5 and Paperclip (obviously).
解决方案:(或至少其中之一)
SOLUTION: (or one of them, at least)
根据 Beerlington 的建议,我决定进行 MD5 校验和比较:
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
然后我在我的 photos
表中添加了一个名为 md5_checksum
的列,瞧!现在,如果您尝试上传同一张照片,我的应用会抛出验证错误!
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!
谢谢!
推荐答案
对图像文件做 MD5 怎么样?如果是完全相同的文件,则两个图像的 MD5 哈希值将相同.
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.
这篇关于Rails:使用回形针防止重复上传照片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!