提交代码

This commit is contained in:
zlwu committed 2025-08-15 23:17:11 +08:00
1 parent c00199b2cf
commit 70ba12e943
1 file changed
+577 -3
@@ -471,8 +471,79 @@
<el-input v-model="form.stayReason" type="textarea" placeholder="请输入留宿原因" :rows="3" />
</el-form-item>
<el-form-item label="附件OSS文件ID" prop="attachmentOssIds">
<el-input v-model="form.attachmentOssIds" type="textarea" placeholder="多个文件ID用逗号分隔" :rows="2" />
<el-form-item label="上传附件">
<div class="attachment-upload-container">
<el-upload
:file-list="attachmentList"
class="upload-demo"
drag
list-type="picture-card"
:on-preview="handleFilePreview"
:action="uploadAction"
:headers="uploadHeaders"
:data="uploadData"
:auto-upload="true"
:before-upload="handleBeforeUpload"
:on-success="handleUploadSuccess"
:on-error="handleUploadError"
:on-remove="handleRemoveAttachmentConfirm"
:on-change="handleFileChange"
multiple
:limit="15"
:show-file-list="true"
accept="image/*,video/*,.pdf,.doc,.docx,.txt"
>
<template #tip>
<div class="el-upload__tip">
支持图片、视频、PDF、Word文档等格式,单个文件大小不超过10MB,最多上传15个文件。
<span class="el-upload__tip" v-if="!form.id" style="color: #ff0000">(新增时文件会立即上传,保存留宿申请后自动关联)</span>
<span class="el-upload__tip" v-else style="color: #ff0000">(编辑时文件会立即上传并关联到当前留宿申请)</span>
</div>
</template>
<!-- 调整拖拽上传图标与文字在同一行、居中对齐 -->
<div class="el-upload-dragger1">
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</div>
<!-- 自定义文件卡片缩略图(含文件名) -->
<template #file="{ file }">
<div class="upload-file-card">
<!-- 缩略图区域 -->
<div class="upload-file-thumb">
<image-preview v-if="isImageFile(file) && file.url" :src="getFileOssId(file)" class="upload-thumb-image" :isOssId="true" />
<div v-else class="upload-file-placeholder">
<el-icon><Document /></el-icon>
<span class="file-ext">{{ getFileExt(file.name) }}</span>
</div>
<!-- loading 遮罩只在上传中显示 -->
<div v-if="file.status === 'uploading'" class="upload-file-loading">
<el-icon class="is-loading"><Loading /></el-icon>
<span class="loading-text">上传中...</span>
</div>
</div>
<!-- 文件名称 -->
<div class="upload-file-name" :title="file.name">
{{ getShortFileName(file.name) }}
</div>
<!-- 操作按钮区域 - 固定在文件名下方 -->
<div class="upload-file-card-actions" v-if="file.status && file.status !== 'ready'">
<el-button-group size="small">
<el-button type="success" @click.stop="handleDownloadAttachment(file)" title="下载" :disabled="file.status !== 'success'">
<el-icon><Download /></el-icon>
</el-button>
<el-button type="danger" @click.stop="handleRemoveAttachmentConfirm(file)" title="删除">
<el-icon><Delete /></el-icon>
</el-button>
</el-button-group>
</div>
</div>
</template>
</el-upload>
</div>
</el-form-item>
<el-form-item label="备注信息" prop="remark">
@@ -490,7 +561,14 @@
</template>
<script setup name="HolidayStay" lang="ts">
import { ref, reactive, toRefs, onMounted, getCurrentInstance, ComponentInternalInstance } from 'vue';
import { ref, reactive, toRefs, onMounted, getCurrentInstance, ComponentInternalInstance, computed } from 'vue';
import ElMessage from 'element-plus/es/components/message/index';
import ElMessageBox from 'element-plus/es/components/message-box/index';
import ElLoading from 'element-plus/es/components/loading/index';
import { UploadFilled, Document, Loading, Download, Delete } from '@element-plus/icons-vue';
import { getToken } from '@/utils/auth';
import ImagePreview from '@/components/ImagePreview/index.vue';
import request from '@/utils/request';
import {
listHolidayStay,
getHolidayStay,
@@ -542,6 +620,9 @@ const roomOptions = ref<RoomOptionVO[]>([]);
const bedOptions = ref<BedOptionVO[]>([]);
const dormLoading = ref(false);
// 附件上传相关状态
const attachmentList = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const holidayStayFormRef = ref<ElFormInstance>();
@@ -645,6 +726,24 @@ const data = reactive<PageData<HolidayStayForm, HolidayStayQuery>>({
const { queryParams, form, rules } = toRefs(data);
// 上传相关配置
const uploadAction = computed(() => {
return import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload';
});
const uploadHeaders = computed(() => {
return {
'Authorization': `Bearer ${getToken() || ''}`,
'clientid': import.meta.env.VITE_APP_CLIENT_ID || 'e5cd7e4891bf95d1d19206ce24a7b32e'
};
});
const uploadData = computed(() => {
return {
bizType: 'holiday_stay_attachment'
};
});
/** 查询假期留宿管理列表 */
const getList = async () => {
loading.value = true;
@@ -670,6 +769,9 @@ const reset = () => {
buildingOptions.value = [];
roomOptions.value = [];
bedOptions.value = [];
// 清空附件列表
attachmentList.value = [];
};
/** 搜索按钮操作 */
@@ -708,6 +810,9 @@ const handleUpdate = async (row?: HolidayStayVO) => {
// 根据已有数据级联加载宿舍选项
await loadCascadeOptionsForUpdate(form.value);
// 处理附件数据
await handleAttachmentData();
dialog.visible = true;
dialog.title = '修改假期留宿管理';
};
@@ -717,6 +822,13 @@ const submitForm = () => {
holidayStayFormRef.value?.validate(async (valid: boolean) => {
if (valid) {
buttonLoading.value = true;
// 处理附件数据
const attachmentOssIds = attachmentList.value.filter((file: any) => file.status === 'success' && file.ossId).map((file: any) => file.ossId);
// 将附件ID添加到表单数据中,处理成逗号分隔的字符串
form.value.attachmentOssIds = attachmentOssIds.join(',');
if (form.value.id) {
await updateHolidayStay(form.value).finally(() => (buttonLoading.value = false));
} else {
@@ -1153,6 +1265,258 @@ const loadCascadeOptionsForUpdate = async (formData: HolidayStayForm) => {
}
};
// 文件类型判断
const isImageFile = (file: any) => {
const imageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
return imageTypes.includes(file.raw?.type) || (file.url && /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file.name));
};
// 获取文件OSS ID的辅助函数
const getFileOssId = (file: any) => {
return file.ossId || '';
};
// 获取文件扩展名
const getFileExt = (fileName: string) => {
const ext = fileName.split('.').pop()?.toUpperCase();
return ext || 'FILE';
};
// 获取缩写的文件名(保留后缀)
const getShortFileName = (fileName: string) => {
if (!fileName) return '';
const lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex === -1) {
// 没有后缀的文件名
return fileName.length > 12 ? fileName.substring(0, 12) + '...' : fileName;
}
const name = fileName.substring(0, lastDotIndex);
const ext = fileName.substring(lastDotIndex); // 包含点号的后缀
if (name.length <= 8) {
return fileName; // 文件名较短,直接返回
}
// 文件名较长,缩写中间部分,保留后缀
return name.substring(0, 8) + '...' + ext;
};
// 文件预览
const handleFilePreview = (file: any) => {
if (isImageFile(file)) {
// 图片预览
window.open(file.url);
} else {
// 其他文件下载
handleDownloadAttachment(file);
}
};
// 文件上传前检查
const handleBeforeUpload = (file: any) => {
const isValidType = /\.(jpg|jpeg|png|gif|bmp|webp|pdf|doc|docx|txt|mp4|avi|mov)$/i.test(file.name);
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isValidType) {
ElMessage.error('上传文件格式不正确!');
return false;
}
if (!isLt10M) {
ElMessage.error('上传文件大小不能超过 10MB!');
return false;
}
return true;
};
// 文件上传成功
const handleUploadSuccess = (response: any, file: any) => {
if (response.code === 200) {
file.url = response.data.url;
file.ossId = response.data.ossId;
ElMessage.success('文件上传成功');
} else {
ElMessage.error(response.msg || '文件上传失败');
}
};
// 文件上传失败
const handleUploadError = (error: any, file: any) => {
console.error('文件上传失败:', error);
ElMessage.error('文件上传失败');
};
// 文件变更
const handleFileChange = (file: any, fileList: any) => {
console.log('文件变更:', file, fileList);
attachmentList.value = fileList;
};
// 删除附件确认
const handleRemoveAttachmentConfirm = (file: any) => {
ElMessageBox.confirm('确定要删除这个文件吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
.then(() => {
handleRemoveAttachment(file);
})
.catch(() => {
// 取消删除
});
};
// 删除附件
const handleRemoveAttachment = (file: any) => {
const index = attachmentList.value.findIndex((item: any) => item.uid === file.uid);
if (index > -1) {
attachmentList.value.splice(index, 1);
ElMessage.success('文件删除成功');
}
};
// 下载附件
const handleDownloadAttachment = async (file: any) => {
let downloadUrl = '';
let fileName = file.name || 'attachment';
// 如果文件已经上传成功,使用服务器返回的路径
if (file.response && file.response.data && file.response.data.filePath) {
downloadUrl = file.response.data.filePath;
fileName = file.response.data.fileName || fileName;
}
// 如果是已有的附件,使用文件的ossId
else if (file.ossId) {
downloadUrl = file.ossId;
}
// 如果是本地文件,直接使用raw文件
else if (file.raw) {
const link = document.createElement('a');
link.href = URL.createObjectURL(file.raw);
link.download = fileName;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
console.log('下载本地文件:', fileName);
return;
}
if (!downloadUrl) {
ElMessage.error('无法获取文件下载地址');
return;
}
// 对于服务器文件,使用fetch获取内容强制下载
try {
const loading = ElLoading.service({
text: '正在下载文件...',
target: document.body
});
const response = await request({
url: '/resource/oss/download/' + downloadUrl,
method: 'get',
responseType: 'blob',
timeout: 300000 // 300秒超时
});
// 验证响应数据
if (!response) {
throw new Error('响应数据为空');
}
console.log('response', response);
// 检查response的结构,判断是直接的Blob还是包含data属性的响应对象
let blobData: Blob;
if (response instanceof Blob) {
// 如果response本身就是Blob对象
blobData = response;
} else if (response.data instanceof Blob) {
// 如果response.data是Blob对象
blobData = response.data;
} else {
throw new Error('无效的响应数据格式');
}
const url = window.URL.createObjectURL(blobData);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
loading?.close();
console.log('下载服务器文件成功:', fileName);
} catch (error) {
console.error('下载文件失败:', error);
ElMessage.error('下载文件失败,请稍后重试');
}
};
// 处理附件数据
const handleAttachmentData = async () => {
try {
// 如果有附件ID,则获取附件信息
if (form.value.attachmentOssIds && form.value.attachmentOssIds.toString().trim()) {
console.log('开始处理附件数据:', form.value.attachmentOssIds);
// 将逗号分隔的字符串转换为数组
const ossIdsArray = form.value.attachmentOssIds
.split(',')
.map((id) => id.trim())
.filter((id) => id);
// 调用接口获取附件信息
const response = await request({
url: `/resource/oss/listByIds/${ossIdsArray.join(',')}`,
method: 'get'
});
if (response.code === 200 && response.data) {
console.log('获取到的附件信息:', response.data);
// 将附件信息转换为上传组件需要的格式
const attachmentFiles = response.data.map((item: any, index: number) => ({
uid: `existing_${index}_${Date.now()}`,
name: item.originalName || `附件${index + 1}`,
url: item.url,
ossId: item.ossId,
status: 'success', // 标记为已上传成功
response: {
code: 200,
data: {
url: item.url,
ossId: item.ossId
}
}
}));
// 设置附件列表
attachmentList.value = attachmentFiles;
console.log('设置附件列表成功:', attachmentList.value);
} else {
console.warn('获取附件信息失败:', response.msg);
attachmentList.value = [];
}
} else {
console.log('没有附件数据,清空附件列表');
attachmentList.value = [];
}
} catch (error) {
console.error('处理附件数据失败:', error);
ElMessage.error('获取附件信息失败,请稍后重试');
attachmentList.value = [];
}
};
onMounted(() => {
getList();
// 加载校区选项
@@ -1217,4 +1581,214 @@ onMounted(() => {
min-height: 32px !important;
padding: 4px 12px !important;
}
/* 附件上传容器样式 */
.attachment-upload-container {
width: 100%;
max-height: calc(100vh - 650px);
min-height: 200px;
overflow-y: auto;
padding-right: 8px;
border: 1px solid #e4e7ed;
border-radius: 6px;
background: #fafafa;
}
/* 附件上传区域内容样式 */
.attachment-upload-container .upload-demo {
padding: 12px;
min-height: 180px;
}
.attachment-upload-container .upload-demo .el-upload {
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
transition: all 0.3s;
}
.attachment-upload-container .upload-demo .el-upload:hover {
border-color: #409eff;
}
.attachment-upload-container .upload-demo .el-upload__tip {
font-size: 12px;
color: #000000;
margin-top: 7px;
}
/* 调整拖拽上传图标与文字在同一行、居中对齐 */
.attachment-upload-container .upload-demo .el-upload-dragger1 {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 15px;
padding: 0px !important;
}
.attachment-upload-container .upload-demo .el-upload-dragger1 .el-icon--upload {
margin: 0;
padding: 0px !important;
}
/* 文件卡片占位封面样式 */
.attachment-upload-container .upload-demo .upload-file-placeholder {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #909399;
font-size: 14px;
}
.attachment-upload-container .upload-demo .upload-file-placeholder .el-icon {
font-size: 28px;
margin-bottom: 4px;
}
.attachment-upload-container .upload-demo .upload-file-placeholder .file-ext {
font-size: 12px;
text-transform: uppercase;
text-align: center;
}
/* 让附件卡片一行展示 5 个 */
.attachment-upload-container :deep(.el-upload-list--picture-card) {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 9px;
margin-top: 12px;
padding-bottom: 16px;
}
/* 确保卡片宽度自适应 */
.attachment-upload-container :deep(.el-upload-list--picture-card) .el-upload-list__item {
margin: 0;
height: 180px !important;
width: 100% !important;
}
:deep(.el-upload-dragger) {
border: 0px !important;
padding: 0px !important;
}
:deep(.el-upload-dragger) .el-upload-dragger1 {
border: 0px !important;
padding: 0px !important;
}
/* 文件卡片样式 */
.upload-file-card {
position: relative;
width: 100%;
height: 100%;
border-radius: 6px;
overflow: hidden;
background: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: all 0.3s;
}
.upload-file-card:hover {
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
.upload-file-thumb {
position: relative;
width: 100%;
height: 110px;
background: #f5f5f5;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.upload-thumb-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.upload-file-loading {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
/* background: rgba(255, 255, 255, 0.9); */
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 10;
}
.loading-text {
margin-top: 8px;
font-size: 12px;
color: #606266;
}
.upload-file-name {
padding: 6px 8px;
font-size: 11px;
color: #303133;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
background: #fafafa;
border-top: 1px solid #f0f0f0;
line-height: 1.2;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
word-break: break-all;
max-width: 100%;
}
.upload-file-card-actions {
display: flex;
justify-content: center;
align-items: center;
padding: 6px 8px;
background: #fafafa;
border-top: 1px solid #f0f0f0;
transition: all 0.3s;
height: 38px;
}
.upload-file-card-actions .el-button-group {
background: transparent;
border-radius: 4px;
padding: 0;
}
.upload-file-card-actions .el-button {
padding: 4px 8px;
border: 1px solid #e0e0e0;
background: #fff;
font-size: 12px;
margin: 0 2px;
border-radius: 3px;
transition: all 0.3s;
}
.upload-file-card-actions .el-button:hover {
background: #f5f5f5;
border-color: #409eff;
}
.upload-file-card-actions .el-button.is-disabled {
opacity: 0.5;
cursor: not-allowed;
background: #f5f5f5;
}
</style>