Files
PORTAL_COD2/src/front/src/components/UI/defaultportal/uploading-file.vue
T

454 lines
13 KiB
Vue

<template>
<v-col>
<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="grey-darken-1"
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>
<template v-if="existingFiles.length">
<v-chip
v-for="file in existingFiles"
:key="file.id"
class="me-2 mb-1"
color="teal-darken-3"
label
@click:close="removeExistingFile(file.id)"
>
<v-icon start class="pb-1">{{ getFileIcon(file) }}</v-icon>
<span class="text-truncate" style="max-width: 120px">
{{ truncateFileName(getFileName(file)) }}
</span>
<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>
<span class="text-caption text-grey">Файлов нет</span>
</template>
</div>
</div>
</v-col>
</template>
<script>
import { computed, ref, watch } from 'vue';
export default {
props: {
files: {
type: Array,
default: () => [],
},
newFiles: {
type: Array,
default: [],
},
},
emits: ['update:files', 'update:newFiles', 'postFiles'],
setup(props, { emit }) {
const localNewFiles = ref([]);
const errorMessages = ref([]);
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 МБ
const MAX_NEW_FILES = 5;
const fileInputRef = ref(null);
watch(
() => props.newFiles,
(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;
const sizes = ['Б', 'КБ', 'МБ', 'ГБ'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
const validateFiles = (files) => {
errorMessages.value = [];
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} файлов`);
return false;
}
// Проверка размера
const oversizedFiles = files.filter((file) => file.size > MAX_FILE_SIZE);
if (oversizedFiles.length > 0) {
errorMessages.value.push(
`Следующие файлы превышают 2 МБ: ${oversizedFiles.map((f) => f.name).join(', ')}`,
);
return false;
}
return true;
};
const getFileKey = (file, index) => {
return file instanceof File
? `${file.name}-${file.size}-${file.lastModified}`
: file.id || index;
};
// Получаем имя файла из объекта файла
const getFileName = (fileData) => {
// Для новых файлов (File object) - берем оригинальное имя
if (fileData instanceof File) {
return fileData.name;
}
// Для существующих файлов с бэкенда - извлекаем из URL
if (fileData.file) {
try {
const filePath = fileData.file.startsWith('http')
? new URL(fileData.file).pathname
: fileData.file;
// Извлекаем имя файла
let fileName = filePath.split('/').pop();
// Декодируем URL-encoded символы, но НЕ изменяем имя
fileName = decodeURIComponent(fileName);
return fileName || 'Файл';
} catch (error) {
console.warn('Ошибка извлечения имени файла:', error, fileData);
return 'Файл';
}
}
// Если есть name в данных - используем как есть
if (fileData.name) {
return fileData.name;
}
return 'Файл';
};
// Иконка в зависимости от типа файла
const getFileIcon = (fileData) => {
let fileName = '';
if (fileData instanceof File) {
fileName = fileData.name;
} else {
fileName = getFileName(fileData);
}
const extension = fileName.split('.').pop()?.toLowerCase() || '';
const iconMap = {
pdf: 'mdi-file-pdf',
doc: 'mdi-file-word',
docx: 'mdi-file-word',
xls: 'mdi-file-excel',
xlsx: 'mdi-file-excel',
jpg: 'mdi-file-image',
jpeg: 'mdi-file-image',
png: 'mdi-file-image',
gif: 'mdi-file-image',
svg: 'mdi-file-image',
zip: 'mdi-folder-zip',
rar: 'mdi-folder-zip',
'7z': 'mdi-folder-zip',
txt: 'mdi-file-document',
json: 'mdi-code-json',
js: 'mdi-language-javascript',
vue: 'mdi-vuejs',
html: 'mdi-language-html5',
css: 'mdi-language-css3',
};
return iconMap[extension] || 'mdi-file';
};
// Обработка изменения новых файлов
const handleFilesChange = (newFiles) => {
if (!newFiles || newFiles.length === 0) {
return;
}
const validFiles = newFiles.filter((file) => file instanceof File);
if (validFiles.length === 0) {
return;
}
// Валидация
if (!validateFiles(validFiles)) {
return;
}
// localNewFiles.value = [...validFiles];
const currentFiles = Array.isArray(localNewFiles.value) ? localNewFiles.value : [];
const updatedFiles = [...currentFiles, ...validFiles];
localNewFiles.value = updatedFiles;
emit('update:newFiles', updatedFiles);
emit('postFiles', updatedFiles);
};
// Удаление существующего файла
const removeExistingFile = (fileId) => {
try {
// Создаем копию event и удаляем файл
const updatedFiles = existingFiles.value.filter((file) => file.id !== fileId);
// props.files = updatedFiles;
emit('update:files', updatedFiles);
} catch (error) {
console.error('Ошибка при удалении файла:', error);
}
};
// Удаление нового файла (еще не загруженного)
const removeNewFile = (index) => {
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 fileName = getFileName(file); // Теперь будет работать правильно!
const fileUrl = file.file.startsWith('http')
? file.file
: `${window.location.origin}${file.file}`; // Для относительных путей
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileName;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
}, 100);
} catch (error) {
console.error('Ошибка при скачивании файла:', error);
errorMessages.value = ['Ошибка скачивания файла'];
}
};
// Функция для обрезки длинных имен файлов
const truncateFileName = (fileName) => {
if (!fileName) return '';
if (fileName.length <= 20) return fileName;
const extension = fileName.split('.').pop();
const nameWithoutExt = fileName.slice(0, -(extension.length + 1));
if (nameWithoutExt.length <= 15) return fileName;
return `${nameWithoutExt.slice(0, 15)}...${extension ? '.' + extension : ''}`;
};
return {
localNewFiles,
existingFiles,
handleFilesChange,
removeExistingFile,
removeNewFile,
getFileName,
getFileIcon,
formatFileSize,
errorMessages,
validateFiles,
getFileKey,
MAX_NEW_FILES,
fileInputRef,
handleFileSelect,
triggerFileInput,
handleDrop,
downloadExistingFile,
truncateFileName,
};
},
};
</script>
<style scoped>
:deep(.v-chip) {
border-radius: 6px;
}
.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: #024e45;
}
.close-icon:hover {
opacity: 1;
color: #024e45;
}
</style>