fix(surveyor): perbaikkan upload foto duplikat

This commit is contained in:
majid
2025-02-26 09:38:52 +07:00
parent 3d7da22ac0
commit 77189701d6
2 changed files with 182 additions and 33 deletions

View File

@@ -506,67 +506,67 @@ class SurveyorController extends Controller
{
if ($request->hasFile($paramName)) {
$files = $request->file($paramName);
// Pastikan $files adalah array
if (!is_array($files)) {
$files = [$files];
}
$formatFotoData = [];
$nomor_registrasi = $request->nomor_registrasi;
// Generate a unique timestamp for this batch
$batchTimestamp = time();
// Create a lookup map of existing file names for faster checking
$existingFileNames = [];
$existingFilePaths = [];
if (isset($formatFotojson[$paramName]) && is_array($formatFotojson[$paramName])) {
foreach ($formatFotojson[$paramName] as $existingFile) {
if (isset($existingFile['name'])) {
$existingFileNames[$existingFile['name']] = true;
if (isset($existingFile['path'])) {
$existingFilePaths[] = $existingFile['path'];
}
}
}
foreach ($files as $index => $file) {
$originalName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$fileNameWithoutExt = pathinfo($originalName, PATHINFO_FILENAME);
// Validasi nama file
if (empty($fileNameWithoutExt)) {
$fileNameWithoutExt = "file_{$batchTimestamp}_{$index}";
}
// Check if this file name already exists in formatFotojson
if (isset($existingFileNames[$fileNameWithoutExt])) {
// File already exists, skip it
continue;
$safeFileName = preg_replace('/[^a-zA-Z0-9_-]/', '_', $fileNameWithoutExt);
$uniqueFileName = "{$batchTimestamp}_{$index}_{$safeFileName}.{$extension}";
$path = "surveyor/{$paramName}/{$nomor_registrasi}/{$uniqueFileName}";
if (in_array($path, $existingFilePaths)) {
$counter = 1;
do {
$uniquePath = "surveyor/{$paramName}/{$nomor_registrasi}/{$batchTimestamp}_{$index}_{$safeFileName}_{$counter}.{$extension}";
$counter++;
} while (in_array($uniquePath, $existingFilePaths));
$path = $uniquePath;
}
// Use batchTimestamp and index to ensure uniqueness in storage
$uniqueFileName = "{$batchTimestamp}_{$index}.{$extension}";
// Simpan file
$path = $file->storeAs("surveyor/{$paramName}/{$nomor_registrasi}", $uniqueFileName, 'public');
$savedPath = $file->storeAs('', $path, 'public');
$existingFilePaths[] = $path;
// Add file data
$fotoData = [
'name' => $fileNameWithoutExt,
'path' => $path,
'path' => $savedPath,
'category' => 'lainnya',
'sub' => null,
'description' => null,
'created_by' => Auth::user()->name,
'created_at' => now()->toDateTimeString(),
];
$formatFotoData[] = $fotoData;
// Add to the lookup map to prevent duplicates within the same batch
$existingFileNames[$fileNameWithoutExt] = true;
}
// Only update if we have new photos to add
if (!empty($formatFotoData)) {
// Struktur JSON yang konsisten
@@ -578,11 +578,11 @@ class SurveyorController extends Controller
$formatFotoData
);
}
return $formatFotoData;
}
}
return [];
}