多文件上传

This commit is contained in:
cwchen 2025-10-28 17:26:06 +08:00
parent e1c2280941
commit 2f8541ea17
2 changed files with 182 additions and 526 deletions

View File

@ -4,36 +4,13 @@
:before-upload="beforeUpload" :on-remove="handleRemove" :on-change="handleFileChange"
:on-exceed="handleExceed" :file-list="files" :accept="accept" :limit="limitUploadNum"
:auto-upload="autoUpload" :http-request="customUpload">
<div class="upload-content">
<!-- 当只有一张图片时显示缩略图 -->
<div v-if="showImagePreview" class="image-preview">
<img :src="previewImageUrl" :alt="previewImageName" class="preview-thumbnail" />
<div class="preview-overlay">
<div class="preview-text">
<div class="main-text">点击更换图片</div>
<div class="tip-text">或拖拽新图片到此处</div>
</div>
</div>
</div>
<!-- 当只有一个文档文件时显示文件图标 -->
<div v-else-if="showFilePreview" class="file-preview">
<div class="file-icon-container">
<i :class="getFileIconClass()" class="file-icon"></i>
<div class="file-name">{{ previewFileName }}</div>
</div>
<div class="preview-overlay">
<div class="preview-text">
<div class="main-text">点击更换文件</div>
<div class="tip-text">或拖拽新文件到此处</div>
</div>
</div>
</div>
<!-- 默认上传区域 -->
<div v-else class="upload-text">
<div class="upload-text">
<div class="main-text"> + 点击或将文件拖拽到这里上传</div>
<div class="tip-text">
<div>最多可上传 {{ limitUploadNum }} 个文件</div>
<div>单份文件大小上限 {{ maxFileTips }}</div>
<div>支持文件类型{{ uploadType }}</div>
</div>
@ -50,6 +27,7 @@ import {
uploadSmallFile,
uploadLargeFile,
} from '@/api/common/uploadFile.js'
export default {
name: 'UploadFile',
props: {
@ -67,7 +45,7 @@ export default {
},
limitUploadNum: {
type: Number,
default: 1,
default: 5,
},
fileUploadRule: {
type: Object,
@ -85,39 +63,22 @@ export default {
data() {
return {
files: [],
previewImageUrl: '',
previewImageName: '',
previewFileName: '',
previewFileType: '',
isUploading: false, //
defaultFileSize: 1024 * 1024 * 5, // 5MB 5MB
skipNextChange: false,
isUploading: false,
uploadingFiles: new Set(),
defaultFileSize: 1024 * 1024 * 5,
uploadControllers: new Map(),
}
},
computed: {
//
showImagePreview() {
return this.previewImageUrl && this.files.length === 1
},
//
showFilePreview() {
return (
this.previewFileName &&
this.previewFileType &&
this.files.length === 1
)
},
accept() {
return this.uploadType
.split('、')
.map((type) => `.${type}`)
.join(',')
},
//
allowedTypes() {
return this.uploadType.split('、')
},
// MB
maxSizeMB() {
const sizeStr = this.maxFileTips.toLowerCase()
if (sizeStr.includes('mb')) {
@ -129,7 +90,6 @@ export default {
}
return 20
},
// MIME
mimeTypes() {
const typeMap = {
png: 'image/png',
@ -148,15 +108,11 @@ export default {
fileList: {
handler(newVal) {
if (this.files.length === 0 && newVal.length > 0) {
// 使 $nextTick DOM
this.$nextTick(() => {
//
if (this.$refs.upload) {
this.$refs.upload.uploadFiles = this.formatFileList(newVal)
}
this.files = this.formatFileList(newVal)
//
this.handlePreviewFromExternal(newVal)
})
}
},
@ -166,20 +122,9 @@ export default {
},
methods: {
beforeUpload(file) {
//
if (this.isUploading) {
this.$message.warning('当前有文件正在上传,请稍后再试')
return false
}
//
const fileExtension = file.name.split('.').pop().toLowerCase()
const isAllowedType = this.allowedTypes.includes(fileExtension)
// MIME
const isAllowedMimeType = this.mimeTypes.includes(file.type)
//
const isLtMaxSize = file.size / 1024 / 1024 < this.maxSizeMB
if (!isAllowedType || !isAllowedMimeType) {
@ -192,150 +137,209 @@ export default {
return false
}
if (this.files.length >= this.limitUploadNum) {
this.$message.error(`最多只能上传 ${this.limitUploadNum} 个文件!`)
return false
}
return true
},
//
handleFileChange(file, fileList) {
//
if (file.status === 'removed' || file.status === 'fail' || file.status === 'success') {
console.log('现在的文件:', this.files);
return
}
//
this.files = this.formatFileList(fileList)
//
if (file.raw && fileList.length === 1) {
if (this.isImageFile(file.raw)) {
//
this.generateImagePreview(file.raw)
} else if (this.isDocumentFile(file.raw)) {
//
this.generateDocumentPreview(file.raw)
}
} else {
//
this.clearPreview()
if (this.autoUpload && file.status === 'ready' && !this.isUploading) {
this.$nextTick(() => {
this.uploadFile(file)
})
}
},
//
handleSuccess(response, file) {
this.$bus.$emit('endUpload')
//
this.updateFileStatus(file.uid, 'success', '', response.data, 100)
//
this.$emit('file-change', this.getCurrentFiles(), this.type)
//
this.isUploading = false
},
//
handleError(error, file) {
console.error('上传失败:', error)
this.$bus.$emit('endUpload')
//
this.removeFailedFile(file.uid)
//
this.isUploading = false
},
//
async customUpload(options) {
console.log(options);
const { file } = options;
//
this.isUploading = true;
const formData = new FormData();
formData.append('file', file);
formData.append('params', JSON.stringify(this.fileUploadRule));
// el-upload
const uploadFileObj = this.findFileByRawFile(file);
if (!uploadFileObj) {
console.error('未找到对应的文件对象');
this.handleError(new Error('文件对象不存在'), file);
return;
async uploadFile(file) {
if (this.uploadingFiles.has(file.uid)) {
return
}
const fileUid = uploadFileObj.uid;
const controller = new AbortController()
this.uploadControllers.set(file.uid, controller)
this.uploadingFiles.add(file.uid)
this.isUploading = true
const formData = new FormData()
formData.append('file', file.raw)
formData.append('params', JSON.stringify(this.fileUploadRule))
// 0
this.updateFileStatus(
fileUid,
file.uid,
'uploading',
this.fileUploadRule.fields_json ? '识别中' : '上传中',
null,
0,
);
)
try {
this.$bus.$emit(
'startUpload',
this.fileUploadRule.fields_json ? '识别中' : '上传中',
);
)
let res = null;
let res = null
if (this.defaultFileSize < file.size) {
if (this.fileUploadRule.fields_json) {
res = await uploadLargeFileByOcr(formData);
res = await uploadLargeFileByOcr(formData, {
signal: controller.signal,
onUploadProgress: (progressEvent) => {
if (progressEvent.lengthComputable) {
const percentComplete = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
this.updateFileStatus(file.uid, 'uploading', '', null, percentComplete)
}
}
})
} else {
res = await uploadLargeFile(formData);
res = await uploadLargeFile(formData, {
signal: controller.signal,
onUploadProgress: (progressEvent) => {
if (progressEvent.lengthComputable) {
const percentComplete = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
this.updateFileStatus(file.uid, 'uploading', '', null, percentComplete)
}
}
})
}
} else {
if (this.fileUploadRule.fields_json) {
res = await uploadSmallFileByOcr(formData);
res = await uploadSmallFileByOcr(formData, {
signal: controller.signal
})
} else {
res = await uploadSmallFile(formData);
res = await uploadSmallFile(formData, {
signal: controller.signal
})
}
}
if (res.code === 200) {
this.handleSuccess(res, uploadFileObj);
this.handleSuccess(res, file)
} else {
this.handleError(new Error(res.message || '上传失败'), uploadFileObj);
this.handleError(new Error(res.message || '上传失败'), file)
}
} catch (err) {
this.handleError(err, uploadFileObj);
if (err.name === 'AbortError') {
console.log('上传已取消:', file.name)
} else {
this.handleError(err, file)
}
} finally {
//
this.isUploading = false;
this.uploadingFiles.delete(file.uid)
this.uploadControllers.delete(file.uid)
this.isUploading = this.uploadingFiles.size > 0
}
},
async customUpload(options) {
const { file } = options
const uploadFileObj = this.findFileByRawFile(file)
if (!uploadFileObj) {
console.error('未找到对应的文件对象')
return
}
this.uploadFile(uploadFileObj)
},
handleSuccess(response, file) {
this.$bus.$emit('endUpload')
this.updateFileStatus(file.uid, 'success', '', response.data, 100)
this.$emit('file-change', this.getCurrentFiles(), this.type)
},
handleError(error, file) {
console.error('上传失败:', error)
this.$bus.$emit('endUpload')
this.updateFileStatus(file.uid, 'fail', error.message)
this.$emit('file-change', this.getCurrentFiles(), this.type)
},
handleExceed(files, fileList) {
this.$message.warning(`最多只能上传 ${this.limitUploadNum} 个文件,已自动截取前 ${this.limitUploadNum} 个文件`);
// FileList
const filesArray = Array.from(files);
const remainingSlots = this.limitUploadNum - this.files.length;
if (remainingSlots > 0) {
const filesToAdd = filesArray.slice(0, remainingSlots);
filesToAdd.forEach(file => {
const newFileObj = this.createFileObject(file);
this.files.push(newFileObj);
if (this.autoUpload) {
this.$nextTick(() => {
this.uploadFile(newFileObj);
});
}
});
}
},
handleRemove(file, fileList) {
if (file == null) {
return true
}
if (file.status === 'uploading') {
this.cancelUpload(file)
}
const delFileObj = this.findFileByRawFile(file.raw)
if (delFileObj) {
delFileObj.response = delFileObj.res
this.$emit('del-file', delFileObj)
}
this.files = this.formatFileList(fileList)
this.$emit('file-change', this.getCurrentFiles(), this.type)
return true
},
cancelUpload(file) {
const controller = this.uploadControllers.get(file.uid)
if (controller) {
controller.abort()
}
this.updateFileStatus(file.uid, 'fail', '上传已取消')
this.uploadingFiles.delete(file.uid)
this.uploadControllers.delete(file.uid)
},
createFileObject(file) {
return {
name: file.name,
size: file.size,
type: file.type,
raw: file,
uid: Date.now() + Math.random(),
status: 'ready',
percentage: 0,
}
},
//
findFileByRawFile(rawFile) {
return this.files.find(item =>
item.raw === rawFile ||
(item.name === rawFile.name && item.size === rawFile.size)
);
},
//
removeFailedFile(fileUid) {
console.log('移除上传失败的文件:', fileUid)
const fileIndex = this.files.findIndex(
(item) => item.uid === fileUid,
)
if (fileIndex !== -1) {
//
this.files.splice(fileIndex, 1)
console.log('移除失败文件后的文件列表:', this.files)
//
this.clearPreview()
//
this.$emit('file-change', this.getCurrentFiles(), this.type)
}
},
//
updateFileStatus(
fileUid,
status,
statusText,
responseData = null,
percentage = null,
) {
const fileIndex = this.files.findIndex(
(item) => item.uid === fileUid,
)
updateFileStatus(fileUid, status, statusText, responseData = null, percentage = null) {
const fileIndex = this.files.findIndex(item => item.uid === fileUid)
if (fileIndex !== -1) {
const updatedFile = {
...this.files[fileIndex],
@ -346,119 +350,26 @@ export default {
updatedFile.statusText = statusText
}
// percentage 0-100
if (
percentage !== null &&
percentage >= 0 &&
percentage <= 100
) {
if (percentage !== null && percentage >= 0 && percentage <= 100) {
updatedFile.percentage = percentage
} else if (status === 'uploading') {
// 0
updatedFile.percentage = 0
} else if (status === 'success') {
// 100
updatedFile.percentage = 100
}
if (responseData) {
//
updatedFile.response = responseData;
updatedFile.response.businessType =
this.fileUploadRule?.fileUploadType;
updatedFile.res = updatedFile.response;
updatedFile.response = responseData
updatedFile.response.businessType = this.fileUploadRule?.fileUploadType
updatedFile.res = updatedFile.response
}
// 使 Vue.set
this.$set(this.files, fileIndex, updatedFile)
console.log('更新后的文件列表:', this.files)
} else {
console.warn('未找到要更新的文件:', fileUid)
}
},
//
handleExceed(files, fileList) {
console.log('文件超出限制处理', files, fileList)
//
if (files.length > 0) {
//
this.$emit('del-file', { ...fileList[0], response: fileList[0].res })
//
this.files = []
//
const newFile = files[0]
// percentage
const newFileObj = {
name: newFile.name,
size: newFile.size,
type: newFile.type,
raw: newFile,
uid: Date.now(), // uid
status: 'ready',
percentage: 0, //
}
//
this.files = [newFileObj]
//
if (this.isImageFile(newFile)) {
this.generateImagePreview(newFile)
} else if (this.isDocumentFile(newFile)) {
this.generateDocumentPreview(newFile)
}
console.log('handleExceed 后的文件列表:', this.files)
//
if (this.autoUpload && !this.isUploading) {
this.$nextTick(() => {
this.$refs.upload.submit();
});
}
}
},
handleRemove(file, fileList) {
if (file == null) {
this.clearPreview();
return true;
}
//
if (this.isUploading && file.status === 'uploading') {
this.$message.warning('文件正在上传中,请稍后再删除');
return false; //
}
//
if (fileList.length === 0) {
this.clearPreview();
} else if (fileList.length === 1 && fileList[0] && fileList[0].raw) {
if (this.isImageFile(fileList[0].raw)) {
this.generateImagePreview(fileList[0].raw);
} else if (this.isDocumentFile(fileList[0].raw)) {
this.generateDocumentPreview(fileList[0].raw);
}
} else {
this.clearPreview();
}
const delFileObj = this.findFileByRawFile(file.raw);
delFileObj.response = delFileObj.res;
//
this.files = this.formatFileList(fileList);
//
this.$emit('del-file', delFileObj);
//
this.$emit('file-change', this.getCurrentFiles(), this.type);
// true false
return true;
},
//
formatFileList(fileList) {
return fileList.map((file) => {
//
const formattedFile = {
uid: file.uid,
name: file.name,
@ -468,40 +379,25 @@ export default {
raw: file.raw,
}
// percentage
if (file.percentage !== undefined && file.percentage !== null) {
formattedFile.percentage = Math.max(
0,
Math.min(100, file.percentage),
)
formattedFile.percentage = Math.max(0, Math.min(100, file.percentage))
} else if (file.status === 'uploading') {
formattedFile.percentage = 0
} else if (file.status === 'success') {
formattedFile.percentage = 100
}
//
if (file.response) {
formattedFile.response = file.response;
formattedFile.res = file.response;
}
if (file.filePath) {
formattedFile.filePath = file.filePath;
}
if (file.statusText) {
formattedFile.statusText = file.statusText
formattedFile.response = file.response
formattedFile.res = file.response
}
return formattedFile
})
},
//
getCurrentFiles() {
const currentFiles = this.files.map((file) => {
return this.files.map((file) => {
const fileObj = {
uid: file.uid,
name: file.name,
@ -510,125 +406,22 @@ export default {
status: file.status,
}
// percentage
if (file.percentage !== undefined) {
fileObj.percentage = file.percentage
}
//
if (file.raw) {
fileObj.raw = file.raw
}
//
if (file.response) {
fileObj.response = file.response
fileObj.response.businessType =
this.fileUploadRule?.fileUploadType
fileObj.response.businessType = this.fileUploadRule?.fileUploadType
}
return fileObj
})
return currentFiles
},
//
isImageFile(file) {
return (
(file && file.type && file.type.startsWith('image/')) ||
(file && file.fileType === '1')
)
},
//
isDocumentFile(file) {
if (!file || !file.name) return false
const fileExtension = file.name.split('.').pop().toLowerCase()
return (
['pdf', 'doc', 'docx', 'xls', 'xlsx'].includes(fileExtension) ||
(file && file.fileType === '2')
)
},
//
generateImagePreview(file) {
const reader = new FileReader()
reader.onload = (e) => {
this.previewImageUrl = e.target.result
this.previewImageName = file.name
//
this.previewFileName = ''
this.previewFileType = ''
}
reader.readAsDataURL(file)
},
//
generateImagePreviewFromPath(file) {
this.previewImageUrl = file.lsFilePath
this.previewImageName = file.name
//
this.previewFileName = ''
this.previewFileType = ''
},
//
generateDocumentPreview(file) {
const fileExtension = file.name.split('.').pop().toLowerCase()
this.previewFileName = file.name
this.previewFileType = fileExtension
//
this.previewImageUrl = ''
this.previewImageName = ''
},
//
clearPreview() {
this.previewImageUrl = ''
this.previewImageName = ''
this.previewFileName = ''
this.previewFileType = ''
},
//
getFileIconClass() {
const iconMap = {
pdf: 'el-icon-document',
doc: 'el-icon-document',
docx: 'el-icon-document',
xls: 'el-icon-document',
xlsx: 'el-icon-document',
}
return iconMap[this.previewFileType] || 'el-icon-document'
},
//
clearFiles() {
this.files = []
this.clearPreview()
this.$emit('file-change', [])
},
//
handlePreviewFromExternal(fileList) {
if (fileList.length > 0) {
const firstFile = fileList[0]
if (firstFile && firstFile.lsFilePath) {
if (this.isImageFile(firstFile)) {
this.generateImagePreviewFromPath(firstFile)
} else if (this.isDocumentFile(firstFile)) {
this.generateDocumentPreview(firstFile)
}
} else if (firstFile && firstFile.raw) {
if (this.isImageFile(firstFile.raw)) {
this.generateImagePreview(firstFile.raw)
} else if (this.isDocumentFile(firstFile.raw)) {
this.generateDocumentPreview(firstFile.raw)
}
} else {
this.clearPreview()
}
} else {
this.clearPreview()
}
},
},
}
</script>
<style scoped lang="scss">
.upload-container {
width: 100%;
@ -641,7 +434,7 @@ export default {
.el-upload-dragger {
width: 100%;
height: 240px;
height: 160px;
border: 2px dashed #dcdfe6;
border-radius: 8px;
background-color: #fafafa;
@ -649,8 +442,6 @@ export default {
align-items: center;
justify-content: center;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
&:hover {
border-color: #409eff;
@ -667,156 +458,22 @@ export default {
flex-direction: column;
align-items: center;
justify-content: center;
padding: 5px;
padding: 20px;
//
.image-preview {
position: relative;
width: 100%;
height: 100%;
border-radius: 6px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
.preview-thumbnail {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
object-fit: contain;
display: block;
}
.preview-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.3s ease;
pointer-events: none;
.preview-text {
text-align: center;
color: white;
pointer-events: none;
.main-text {
font-size: 16px;
margin-bottom: 8px;
font-weight: 500;
}
.tip-text {
font-size: 12px;
opacity: 0.9;
}
}
}
&:hover .preview-overlay {
opacity: 1;
}
}
//
.file-preview {
position: relative;
width: 100%;
height: 100%;
border-radius: 6px;
overflow: hidden;
.file-icon-container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #f9fafc;
.file-icon {
font-size: 64px;
color: #1f72ea;
margin-bottom: 16px;
}
.file-name {
font-size: 14px;
color: #606266;
text-align: center;
padding: 0 20px;
word-break: break-all;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
}
}
.preview-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.3s ease;
pointer-events: none;
.preview-text {
text-align: center;
color: white;
pointer-events: none;
.main-text {
font-size: 16px;
margin-bottom: 8px;
font-weight: 500;
}
.tip-text {
font-size: 12px;
opacity: 0.9;
}
}
}
&:hover .preview-overlay {
opacity: 1;
}
}
//
.upload-text {
text-align: center;
.main-text {
font-size: 18px;
font-size: 16px;
color: #1f72ea;
margin-bottom: 12px;
margin-bottom: 8px;
font-weight: 500;
}
.tip-text {
font-size: 14px;
color: #909399;
line-height: 1.5;
line-height: 1.4;
div {
margin-bottom: 2px;
@ -825,4 +482,4 @@ export default {
}
}
}
</style>
</style>

View File

@ -20,13 +20,13 @@
const defaultParams = {
fileType: 'technical_solution',
uploadType: 'pdf、doc、docx',
maxFileTips: '1MB',
maxFileTips: '500MB',
fileUploadRule: {
fileUploadType: 'technical_solution',
fields_json: '',
suffix: 'technical_solution_database'
},
limitUploadNum: 10
limitUploadNum: 5
};
import UploadMoreFile from '@/views/common/UploadMoreFile.vue'
export default {
@ -84,7 +84,6 @@ export default {
//
handleDelFile(file) {
const delPath = file?.response?.fileRes?.filePath || file?.filePath || null;
alert(delPath);
if(delPath){
this.form.delFileList.push(delPath);
}