fix [P-47]: прикрепление файлов

This commit is contained in:
Inna committed 2025-09-29 13:19:37 +03:00
1 parent 739d2f03be
commit c073b4422f
2 files changed
+244 -49

No files matched your search

@@ -1,19 +1,23 @@
<template> <template>
<v-col> <v-col>
<v-file-input <div class="custom-file-input-wrapper">
label="Добавить файл (размер файла не должен превышать 2Мб)" <label class="v-label v-field-label v-field-label--floating">
chips Добавить файл (размер файла не должен превышать 2Мб)
multiple </label>
v-model="localNewFiles"
density="compact" <!-- Область, куда можно перетащить файлы -->
variant="outlined" <div
:error-messages="errorMessages" class="file-input-area"
@update:model-value="handleFilesChange" @click="triggerFileInput"
@drop="handleDrop"
@dragover.prevent
@dragenter.prevent
> >
<template v-slot:selection> <!-- Кастомные чипы новых файлов ВНУТРИ "инпута" -->
<div class="chips-container" v-if="localNewFiles.length > 0">
<template v-for="(file, index) in localNewFiles" :key="getFileKey(file, index)"> <template v-for="(file, index) in localNewFiles" :key="getFileKey(file, index)">
<v-chip <v-chip
class="me-2 mb-1" class="file-chip"
color="teal-darken-3" color="teal-darken-3"
size="small" size="small"
label label
@@ -21,19 +25,43 @@
@click:close="removeNewFile(index)" @click:close="removeNewFile(index)"
> >
<v-icon start size="small">mdi-file-plus</v-icon> <v-icon start size="small">mdi-file-plus</v-icon>
<span class="text-truncate" style="max-width: 120px"> <span class="text-truncate" style="max-width: 100px">
{{ file.name }}({{ formatFileSize(file.size) }}) {{ file.name }}({{ formatFileSize(file.size) }})
</span> </span>
</v-chip> </v-chip>
</template> </template>
<!-- <span v-if="newFiles.length > 0" class="text-caption text-grey ms-2"> <span class="file-counter text-caption text-grey">
{{ localNewFiles.length }}/5 {{ localNewFiles.length }}/{{ MAX_NEW_FILES }}
</span> --> </span>
</template> </div>
</v-file-input>
<!-- Существующие файлы отдельно --> <!-- Плейсхолдер, когда файлов нет -->
<div v-else class="placeholder">
<v-icon class="me-1">mdi-paperclip</v-icon>
<span class="text-caption">Перетащите файлы сюда или кликните для выбора</span>
</div>
<!-- Скрытый настоящий input -->
<input
ref="fileInputRef"
type="file"
multiple
style="display: none"
@change="handleFileSelect"
/>
</div>
<!-- Область ошибок -->
<div class="error-messages" v-if="errorMessages.length">
<div v-for="(error, index) in errorMessages" :key="index" class="text-caption text-error">
{{ error }}
</div>
</div>
</div>
<!-- Существующие файлы из БД -->
<div class="existing-files-section mb-4"> <div class="existing-files-section mb-4">
<div class="text-caption text-grey mb-2">Прикрепленный файл:</div> <div class="text-caption text-grey mb-2">Прикрепленные файлы:</div>
<div> <div>
<template v-if="existingFiles.length"> <template v-if="existingFiles.length">
<v-chip <v-chip
@@ -41,13 +69,25 @@
:key="file.id" :key="file.id"
class="me-2 mb-1 " class="me-2 mb-1 "
color="grey-darken-1" color="grey-darken-1"
size="small"
label label
closable
@click:close="removeExistingFile(file.id)" @click:close="removeExistingFile(file.id)"
> >
<v-icon start size="small">{{ getFileIcon(file) }}</v-icon> <v-icon start class="pb-1">{{ getFileIcon(file) }}</v-icon>
{{ getFileName(file) }} {{ getFileName(file) }}
<v-icon
class="ms-1 download-icon"
@click.stop="downloadExistingFile(file)"
title="Скачать файл"
>
mdi-download
</v-icon>
<v-icon
class="ms-1 close-icon"
@click.stop="removeExistingFile(file.id)"
title="Удалить файл"
>
mdi-close
</v-icon>
</v-chip> </v-chip>
</template> </template>
<template v-else> <template v-else>
@@ -79,14 +119,43 @@ export default {
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 МБ const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 МБ
const MAX_NEW_FILES = 5; const MAX_NEW_FILES = 5;
const fileInputRef = ref(null);
watch( watch(
() => props.newFiles, () => props.newFiles,
(newVal) => { (newVal) => {
localNewFiles.value = [...newVal]; localNewFiles.value = Array.isArray(newVal) ? [...newVal] : [];
}, },
{ immediate: true }, { immediate: true },
); );
// Существующие файлы из event.files
const existingFiles = computed(() => (Array.isArray(props.files) ? props.files : []));
const triggerFileInput = () => {
if (fileInputRef.value) {
fileInputRef.value.click();
}
};
const handleFileSelect = (event) => {
const files = Array.from(event.target.files || []);
if (files.length > 0) {
handleFilesChange(files);
}
// Очищаем input для возможности выбора тех же файлов снова
event.target.value = '';
};
// Обработка drag & drop
const handleDrop = (event) => {
event.preventDefault();
const files = Array.from(event.dataTransfer.files || []);
if (files.length > 0) {
handleFilesChange(files);
}
};
const formatFileSize = (bytes) => { const formatFileSize = (bytes) => {
if (bytes === 0) return '0 Б'; if (bytes === 0) return '0 Б';
const k = 1024; const k = 1024;
@@ -98,7 +167,9 @@ export default {
const validateFiles = (files) => { const validateFiles = (files) => {
errorMessages.value = []; errorMessages.value = [];
const totalFiles = localNewFiles.value.length + files.length; const currentFiles = Array.isArray(localNewFiles.value) ? localNewFiles.value : [];
const totalFiles = currentFiles.length + files.length;
// Проверка количества // Проверка количества
if (totalFiles > MAX_NEW_FILES) { if (totalFiles > MAX_NEW_FILES) {
errorMessages.value.push(`Можно добавить не более ${MAX_NEW_FILES} файлов`); errorMessages.value.push(`Можно добавить не более ${MAX_NEW_FILES} файлов`);
@@ -116,8 +187,6 @@ export default {
return true; return true;
}; };
// Существующие файлы из event.files
const existingFiles = computed(() => (Array.isArray(props.files) ? props.files : []));
const getFileKey = (file, index) => { const getFileKey = (file, index) => {
return file instanceof File return file instanceof File
@@ -128,20 +197,25 @@ export default {
// Получаем имя файла из объекта файла // Получаем имя файла из объекта файла
const getFileName = (fileData) => { const getFileName = (fileData) => {
if (fileData instanceof File) { if (fileData instanceof File) {
return fileData.name; return cleanFileName(fileData.name);
} }
// Для существующих файлов с бэка - извлекаем имя из пути // Для существующих файлов с бэка - извлекаем имя из пути
if (fileData.file) { if (fileData.file) {
try { try {
const filePath = fileData.file.split('?')[0]; // Убираем параметры const filePath = fileData.file.split('?')[0]; // Убираем параметры
const fileName = filePath.split('/').pop(); // Берем последнюю часть пути const fileName = filePath.split('/').pop(); // Берем последнюю часть пути
return fileName || 'Файл'; return cleanFileName(fileName) || 'Файл';
} catch { } catch {
return 'Файл'; return 'Файл';
} }
} }
return 'Файл'; return cleanFileName(fileData.name || 'Файл');
};
const cleanFileName = (fileName) => {
// Убираем суффиксы в скобках (1), (2) и т.д.
return fileName.replace(/\s*\(\d+\)(?=\.\w+$|$)/, '');
}; };
// Иконка в зависимости от типа файла // Иконка в зависимости от типа файла
@@ -180,15 +254,12 @@ export default {
}; };
// Обработка изменения новых файлов // Обработка изменения новых файлов
const handleFilesChange = (files) => { const handleFilesChange = (newFiles) => {
if (!newFiles || newFiles.length === 0) {
if (!files) {
// localNewFiles.value = [];
emit('postFiles', []);
return; return;
} }
const validFiles = files.filter((file) => file instanceof File);
const validFiles = newFiles.filter((file) => file instanceof File);
if (validFiles.length === 0) { if (validFiles.length === 0) {
return; return;
@@ -199,17 +270,20 @@ export default {
return; return;
} }
localNewFiles.value = [...validFiles]; // localNewFiles.value = [...validFiles];
const currentFiles = Array.isArray(localNewFiles.value) ? localNewFiles.value : [];
const updatedFiles = [...currentFiles, ...validFiles];
localNewFiles.value = updatedFiles;
emit('update:newFiles', validFiles); emit('update:newFiles', updatedFiles);
emit('postFiles', validFiles); emit('postFiles', updatedFiles);
}; };
// Удаление существующего файла // Удаление существующего файла
const removeExistingFile = (fileId) => { const removeExistingFile = (fileId) => {
try { try {
// Создаем копию event и удаляем файл // Создаем копию event и удаляем файл
const updatedFiles = props.files.filter((file) => file.id !== fileId); const updatedFiles = existingFiles.value.filter((file) => file.id !== fileId);
// props.files = updatedFiles; // props.files = updatedFiles;
emit('update:files', updatedFiles); emit('update:files', updatedFiles);
} catch (error) { } catch (error) {
@@ -219,8 +293,38 @@ export default {
// Удаление нового файла (еще не загруженного) // Удаление нового файла (еще не загруженного)
const removeNewFile = (index) => { const removeNewFile = (index) => {
localNewFiles.value.splice(index, 1); const updatedFiles = localNewFiles.value.filter((_, i) => i !== index);
emit('postFiles', localNewFiles.value); localNewFiles.value = updatedFiles;
// localNewFiles.value.splice(index, 1);
// emit('postFiles', localNewFiles.value);
emit('update:newFiles', updatedFiles);
emit('postFiles', updatedFiles);
};
const downloadExistingFile = async (file) => {
try {
const getOriginalFileName = (filePath) => {
try {
const pathParts = filePath.split('/');
return pathParts[pathParts.length - 1];
} catch {
return 'file';
}
};
const fileName = getOriginalFileName(file.file);
const fileUrl = file.file;
// Создаем временную ссылку для скачивания
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileName; // Указываем имя файла при скачивании
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.error('Ошибка при скачивании файла:', error);
}
}; };
return { return {
@@ -235,6 +339,13 @@ export default {
errorMessages, errorMessages,
validateFiles, validateFiles,
getFileKey, getFileKey,
MAX_NEW_FILES,
fileInputRef,
handleFileSelect,
triggerFileInput,
handleDrop,
cleanFileName,
downloadExistingFile,
}; };
}, },
}; };
@@ -245,7 +356,75 @@ export default {
border-radius: 6px; border-radius: 6px;
} }
.v-file-input__selection { .custom-file-input-wrapper {
display: none !important; border: 1px solid rgba(0, 0, 0, 0.38);
border-radius: 4px;
padding: 12px;
position: relative;
background-color: white;
} }
.custom-file-input-wrapper:focus-within {
border-color: #1976d2;
border-width: 2px;
}
.file-input-area {
min-height: 40px;
cursor: pointer;
padding: 4px;
}
.chips-container {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
}
.file-chip {
max-width: 150px;
}
.file-counter {
margin-left: 8px;
}
.placeholder {
display: flex;
align-items: center;
color: rgba(0, 0, 0, 0.6);
padding: 8px 0;
}
.error-messages {
margin-top: 4px;
}
.text-error {
color: #d32f2f;
}
.existing-files-section {
border-top: 1px solid #e0e0e0;
padding-top: 16px;
}
.download-icon {
cursor: pointer;
opacity: 0.7;
transition: opacity 0.2s;
}
.download-icon:hover {
opacity: 1;
color: #5e6061;
}
.close-icon:hover {
opacity: 1;
color: #383a3a;
}
</style> </style>
@@ -147,16 +147,15 @@
> >
<v-row <v-row
no-gutters no-gutters
class="align-start d-flex pt-3" class="align-start d-flex pt-3 mb-3"
style="min-height: 180px; max-height: 180px" style=" height:auto; min-height: 200px; max-height: 400px"
> >
<v-col class="text-body-2 text-text_grey pb-5 pt-3" lg="2"> Файлы </v-col> <v-col class="text-body-2 text-text_grey pb-5 pt-3" lg="2"> Файлы </v-col>
<uploading-file <uploading-file
v-model:new-files="newFiles" v-model:new-files="newFiles"
@update:model-value="newFiles = $event"
:files="propsEvent.event.files" :files="propsEvent.event.files"
@update:files="propsEvent.event.files = $event" @update:files="handleFilesUpdate"
@postFiles="postFiles" @postFiles="postFiles"
/> />
</v-row> </v-row>
@@ -444,6 +443,17 @@ export default {
const newFiles = ref([]); const newFiles = ref([]);
const handleFilesUpdate = (updatedExistingFiles) => {
// Сохраняем новые файлы во временную переменную
const currentNewFiles = [...newFiles.value];
// Обновляем существующие файлы
propsEvent.value.event.files = updatedExistingFiles;
// Восстанавливаем новые файлы
newFiles.value = currentNewFiles;
};
const postFiles = (updatedFiles) => { const postFiles = (updatedFiles) => {
newFiles.value = updatedFiles; newFiles.value = updatedFiles;
}; };
@@ -483,7 +493,12 @@ export default {
propsEvent.value.event.calendar = myCalendar.value.id; propsEvent.value.event.calendar = myCalendar.value.id;
let postEvent = new FormData(); let postEvent = new FormData();
postEvent.append('event', JSON.stringify({ ...propsEvent.value.event, files: [] }));
postEvent.append(
'event',
JSON.stringify({ ...propsEvent.value.event, files: propsEvent.value.event.files }),
);
if (propsEvent.value.event.files !== null) { if (propsEvent.value.event.files !== null) {
newFiles.value.forEach((e) => postEvent.append('files', e)); newFiles.value.forEach((e) => postEvent.append('files', e));
} }
@@ -595,6 +610,7 @@ export default {
createDialog, createDialog,
handleAutoAdjustEnd, handleAutoAdjustEnd,
newFiles, newFiles,
handleFilesUpdate,
}; };
}, },
}; };