I have a content type, Image, which allows users to add an image using Drupal 7's built-in image field. I would like to automatically prevent users from adding the exact same image (same filename, same size) if possible. Is there any way to prevent duplicate file uploads?
In pseudo/quick code, this is how I would approach it. In a custom module...
Create a table in the db, with two columns, fid and md5.
Each time you create a file, check if the md5() of whatever you consider unique is in that db, eg:
a. select fid from TABLE where md5 = ab3783ea6c83bcd9383eef778
b. if fid then oops, there already appears to be file blah blah blah
Store that file's fid and md5() in that table.
You could put all this logic in the validation hook when you are creating the image content. You could even set up roles that are able to override it, etc.
Now, to the md5()ing of things.
Filename is easily changed and I don't think it is really sent to drupal anyway--but instead crafted there after the fact--so do you really want to use it?
Content of the file might be a better approach.
So, md5 could be populated with a quick md5_file(PATHTOFILE).
Now, let's say you wanted to have an option of doing this system wide or per user, eg, you don't want one user uploading multiple copies of one image or you want to have only one exact image uploaded systemwide.
Just add another column uid to the table above and check it as well, eg:
select fid from TABLE where md5 = ... and uid = $user->uid
Anyway, these are just my quick thoughts after the morning's first espresso here in D6land. Maybe D7 has some of this already built into it and I am once again reinventing that wheel :)
I think you need to write a custom module to achieve this. I have done this before in bits and pieces. Use a form alter and see for the fields. In that get the name and the size of the file, sure some variable would have got these two.
- Try if you can get these values from Database using db_query.
- If not save them dynamically using the "static $variable_name = $field['name']; and similarly for size also.
Now try to use a if() and see if(!isset($field['name']) && !isset($field['size'])). And based on this set the error message in the form.
Hope it helps you.