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
+260 -65

No files matched your search

@@ -1,53 +1,93 @@
<template>
<v-col>
<v-file-input
label="Добавить файл (размер файла не должен превышать 2Мб)"
chips
multiple
v-model="localNewFiles"
density="compact"
variant="outlined"
:error-messages="errorMessages"
@update:model-value="handleFilesChange"
>
<template v-slot:selection>
<template v-for="(file, index) in localNewFiles" :key="getFileKey(file, index)">
<v-chip
class="me-2 mb-1"
color="teal-darken-3"
size="small"
label
closable
@click:close="removeNewFile(index)"
>
<v-icon start size="small">mdi-file-plus</v-icon>
<span class="text-truncate" style="max-width: 120px">
{{ file.name }}({{ formatFileSize(file.size) }})
</span>
</v-chip>
</template>
<!-- <span v-if="newFiles.length > 0" class="text-caption text-grey ms-2">
{{ localNewFiles.length }}/5
</span> -->
</template>
</v-file-input>
<!-- Существующие файлы отдельно -->
<div class="custom-file-input-wrapper">
<label class="v-label v-field-label v-field-label--floating">
Добавить файл (размер файла не должен превышать 2Мб)
</label>
<!-- Область, куда можно перетащить файлы -->
<div
class="file-input-area"
@click="triggerFileInput"
@drop="handleDrop"
@dragover.prevent
@dragenter.prevent
>
<!-- Кастомные чипы новых файлов ВНУТРИ "инпута" -->
<div class="chips-container" v-if="localNewFiles.length > 0">
<template v-for="(file, index) in localNewFiles" :key="getFileKey(file, index)">
<v-chip
class="file-chip"
color="teal-darken-3"
size="small"
label
closable
@click:close="removeNewFile(index)"
>
<v-icon start size="small">mdi-file-plus</v-icon>
<span class="text-truncate" style="max-width: 100px">
{{ file.name }}({{ formatFileSize(file.size) }})
</span>
</v-chip>
</template>
<span class="file-counter text-caption text-grey">
{{ localNewFiles.length }}/{{ MAX_NEW_FILES }}
</span>
</div>
<!-- Плейсхолдер, когда файлов нет -->
<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="text-caption text-grey mb-2">Прикрепленный файл:</div>
<div class="text-caption text-grey mb-2">Прикрепленные файлы:</div>
<div>
<template v-if="existingFiles.length">
<v-chip
v-for="file in existingFiles"
:key="file.id"
class="me-2 mb-1"
class="me-2 mb-1 "
color="grey-darken-1"
size="small"
label
closable
@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) }}
<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>
</template>
<template v-else>
@@ -71,7 +111,7 @@ export default {
default: [],
},
},
emits: ['update:files', 'update: newFiles', 'postFiles'],
emits: ['update:files', 'update:newFiles', 'postFiles'],
setup(props, { emit }) {
const localNewFiles = ref([]);
@@ -79,14 +119,43 @@ export default {
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 МБ
const MAX_NEW_FILES = 5;
const fileInputRef = ref(null);
watch(
() => props.newFiles,
(newVal) => {
localNewFiles.value = [...newVal];
localNewFiles.value = Array.isArray(newVal) ? [...newVal] : [];
},
{ 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) => {
if (bytes === 0) return '0 Б';
const k = 1024;
@@ -98,7 +167,9 @@ export default {
const validateFiles = (files) => {
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) {
errorMessages.value.push(`Можно добавить не более ${MAX_NEW_FILES} файлов`);
@@ -116,8 +187,6 @@ export default {
return true;
};
// Существующие файлы из event.files
const existingFiles = computed(() => (Array.isArray(props.files) ? props.files : []));
const getFileKey = (file, index) => {
return file instanceof File
@@ -128,20 +197,25 @@ export default {
// Получаем имя файла из объекта файла
const getFileName = (fileData) => {
if (fileData instanceof File) {
return fileData.name;
return cleanFileName(fileData.name);
}
// Для существующих файлов с бэка - извлекаем имя из пути
if (fileData.file) {
try {
const filePath = fileData.file.split('?')[0]; // Убираем параметры
const fileName = filePath.split('/').pop(); // Берем последнюю часть пути
return fileName || 'Файл';
return cleanFileName(fileName) || 'Файл';
} catch {
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) => {
if (!files) {
// localNewFiles.value = [];
emit('postFiles', []);
const handleFilesChange = (newFiles) => {
if (!newFiles || newFiles.length === 0) {
return;
}
const validFiles = files.filter((file) => file instanceof File);
const validFiles = newFiles.filter((file) => file instanceof File);
if (validFiles.length === 0) {
return;
@@ -199,17 +270,20 @@ export default {
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('postFiles', validFiles);
emit('update:newFiles', updatedFiles);
emit('postFiles', updatedFiles);
};
// Удаление существующего файла
const removeExistingFile = (fileId) => {
try {
// Создаем копию event и удаляем файл
const updatedFiles = props.files.filter((file) => file.id !== fileId);
const updatedFiles = existingFiles.value.filter((file) => file.id !== fileId);
// props.files = updatedFiles;
emit('update:files', updatedFiles);
} catch (error) {
@@ -219,8 +293,38 @@ export default {
// Удаление нового файла (еще не загруженного)
const removeNewFile = (index) => {
localNewFiles.value.splice(index, 1);
emit('postFiles', localNewFiles.value);
const updatedFiles = localNewFiles.value.filter((_, i) => i !== index);
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 {
@@ -235,6 +339,13 @@ export default {
errorMessages,
validateFiles,
getFileKey,
MAX_NEW_FILES,
fileInputRef,
handleFileSelect,
triggerFileInput,
handleDrop,
cleanFileName,
downloadExistingFile,
};
},
};
@@ -245,7 +356,75 @@ export default {
border-radius: 6px;
}
.v-file-input__selection {
display: none !important;
.custom-file-input-wrapper {
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>
@@ -147,16 +147,15 @@
>
<v-row
no-gutters
class="align-start d-flex pt-3"
style="min-height: 180px; max-height: 180px"
class="align-start d-flex pt-3 mb-3"
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>
<uploading-file
v-model:new-files="newFiles"
@update:model-value="newFiles = $event"
:files="propsEvent.event.files"
@update:files="propsEvent.event.files = $event"
@update:files="handleFilesUpdate"
@postFiles="postFiles"
/>
</v-row>
@@ -444,6 +443,17 @@ export default {
const newFiles = ref([]);
const handleFilesUpdate = (updatedExistingFiles) => {
// Сохраняем новые файлы во временную переменную
const currentNewFiles = [...newFiles.value];
// Обновляем существующие файлы
propsEvent.value.event.files = updatedExistingFiles;
// Восстанавливаем новые файлы
newFiles.value = currentNewFiles;
};
const postFiles = (updatedFiles) => {
newFiles.value = updatedFiles;
};
@@ -483,7 +493,12 @@ export default {
propsEvent.value.event.calendar = myCalendar.value.id;
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) {
newFiles.value.forEach((e) => postEvent.append('files', e));
}
@@ -595,6 +610,7 @@ export default {
createDialog,
handleAutoAdjustEnd,
newFiles,
handleFilesUpdate,
};
},
};