By parthabapari on
Could some one help me to prevent uploading file with the same name and extension. By default Drupal add _0,_1.._n to the files with same name and extension. I am using filehash module to prevent uploading identical file which works great but I need to prevent file with the same name and extension regardless they might be different files.
Comments
You can try the File
You can try the File Temporary Validator module. The module compares the name of the uploaded file with names of files that have the "Temporary" status. In Drupal, Temporary files generally kept for some time — default 6 hours — before being deleted. You can configure this time by visiting the following page:
/admin/config/media/file-system
The module won't work for the case when you need to compare the name of the uploaded file with names of files that have "Permanent" status. But if necessary we can create a solution for this.
Thanks wombatbuddy for your
Thanks wombatbuddy for your reply. In my case I need to check uploaded file with an existing permanent status file.
I wrote the below code which works when I upload file using File field but this fails when uploading using Entity reference media. The reason is $file->getFilename() returns the original file name when uploading file using File field type but media entity returns with suffix _0, _1 ....
I would highly appreciate if you could provide a solution.
function file_name_check_file_validate(\Drupal\file\FileInterface $file) {
$file_name = $file->getFilename();
$statement = \Drupal::database()->query("SELECT COUNT(*) FROM {file_managed} WHERE filename = :fname AND status = :status", [':fname' => $file_name, ':status' => 1]);
$count = $statement->fetchField();
// If files exist with the same name, prevent upload.
if ($count > 0) {
$errors = [];
// Set the error message to indicate file conflict.
$errors[] = t("A file with the same name and extension already exists.");
// Prevent file save by returning early.
return $errors;
}
}
If you have a budget for it,
If you have a budget for it, you may contact me.