smart-bid-web/src/views/common/UploadMoreFile.vue

485 lines
16 KiB
Vue
Raw Normal View History

2025-10-28 16:52:31 +08:00
<template>
<div class="upload-container">
<el-upload ref="upload" class="upload-demo" drag action="#" multiple :show-file-list="true"
: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">
2025-10-28 17:26:06 +08:00
<div class="upload-content">
2025-10-28 16:52:31 +08:00
<!-- 默认上传区域 -->
2025-10-28 17:26:06 +08:00
<div class="upload-text">
2025-10-28 16:52:31 +08:00
<div class="main-text"> + 点击或将文件拖拽到这里上传</div>
<div class="tip-text">
2025-10-28 17:26:06 +08:00
<div>最多可上传 {{ limitUploadNum }} 个文件</div>
2025-10-28 16:52:31 +08:00
<div>单份文件大小上限 {{ maxFileTips }}</div>
<div>支持文件类型{{ uploadType }}</div>
</div>
</div>
</div>
</el-upload>
</div>
</template>
<script>
import {
uploadSmallFileByOcr,
uploadLargeFileByOcr,
uploadSmallFile,
uploadLargeFile,
} from '@/api/common/uploadFile.js'
2025-10-28 17:26:06 +08:00
2025-10-28 16:52:31 +08:00
export default {
name: 'UploadFile',
props: {
fileList: {
type: Array,
default: () => [],
},
maxFileTips: {
type: String,
default: '20MB',
},
uploadType: {
type: String,
default: 'png、jpg、jpeg',
},
limitUploadNum: {
type: Number,
2025-10-28 17:26:06 +08:00
default: 5,
2025-10-28 16:52:31 +08:00
},
fileUploadRule: {
type: Object,
default: () => ({}),
},
autoUpload: {
type: Boolean,
default: true,
},
type: {
type: String,
default: '',
},
},
data() {
return {
files: [],
2025-10-28 17:26:06 +08:00
isUploading: false,
uploadingFiles: new Set(),
defaultFileSize: 1024 * 1024 * 5,
uploadControllers: new Map(),
2025-10-28 16:52:31 +08:00
}
},
computed: {
accept() {
return this.uploadType
.split('、')
.map((type) => `.${type}`)
.join(',')
},
allowedTypes() {
return this.uploadType.split('、')
},
maxSizeMB() {
const sizeStr = this.maxFileTips.toLowerCase()
if (sizeStr.includes('mb')) {
return parseFloat(sizeStr)
} else if (sizeStr.includes('kb')) {
return parseFloat(sizeStr) / 1024
} else if (sizeStr.includes('gb')) {
return parseFloat(sizeStr) * 1024
}
return 20
},
mimeTypes() {
const typeMap = {
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
pdf: 'application/pdf',
doc: 'application/msword',
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
xls: 'application/vnd.ms-excel',
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}
return this.allowedTypes.map((type) => typeMap[type] || '')
},
},
watch: {
fileList: {
handler(newVal) {
if (this.files.length === 0 && newVal.length > 0) {
this.$nextTick(() => {
if (this.$refs.upload) {
this.$refs.upload.uploadFiles = this.formatFileList(newVal)
}
this.files = this.formatFileList(newVal)
})
}
},
immediate: true,
deep: true
},
},
methods: {
beforeUpload(file) {
const fileExtension = file.name.split('.').pop().toLowerCase()
const isAllowedType = this.allowedTypes.includes(fileExtension)
const isAllowedMimeType = this.mimeTypes.includes(file.type)
const isLtMaxSize = file.size / 1024 / 1024 < this.maxSizeMB
if (!isAllowedType || !isAllowedMimeType) {
this.$message.error(`只能上传 ${this.uploadType} 格式的文件!`)
return false
}
if (!isLtMaxSize) {
this.$message.error(`文件大小不能超过 ${this.maxFileTips}!`)
return false
}
2025-10-28 17:26:06 +08:00
if (this.files.length >= this.limitUploadNum) {
this.$message.error(`最多只能上传 ${this.limitUploadNum} 个文件!`)
return false
}
2025-10-28 16:52:31 +08:00
return true
},
2025-10-28 17:26:06 +08:00
2025-10-28 16:52:31 +08:00
handleFileChange(file, fileList) {
if (file.status === 'removed' || file.status === 'fail' || file.status === 'success') {
return
}
2025-10-28 17:26:06 +08:00
this.files = this.formatFileList(fileList)
2025-10-28 16:52:31 +08:00
2025-10-28 17:26:06 +08:00
if (this.autoUpload && file.status === 'ready' && !this.isUploading) {
this.$nextTick(() => {
this.uploadFile(file)
})
}
2025-10-28 16:52:31 +08:00
},
2025-10-28 17:26:06 +08:00
async uploadFile(file) {
if (this.uploadingFiles.has(file.uid)) {
return
2025-10-28 16:52:31 +08:00
}
2025-10-28 17:26:06 +08:00
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))
2025-10-28 16:52:31 +08:00
this.updateFileStatus(
2025-10-28 17:26:06 +08:00
file.uid,
2025-10-28 16:52:31 +08:00
'uploading',
this.fileUploadRule.fields_json ? '识别中' : '上传中',
null,
0,
2025-10-28 17:26:06 +08:00
)
2025-10-28 16:52:31 +08:00
try {
this.$bus.$emit(
'startUpload',
this.fileUploadRule.fields_json ? '识别中' : '上传中',
2025-10-28 17:26:06 +08:00
)
2025-10-28 16:52:31 +08:00
2025-10-28 17:26:06 +08:00
let res = null
2025-10-28 16:52:31 +08:00
if (this.defaultFileSize < file.size) {
if (this.fileUploadRule.fields_json) {
2025-10-28 17:26:06 +08:00
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)
}
}
})
2025-10-28 16:52:31 +08:00
} else {
2025-10-28 17:26:06 +08:00
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)
}
}
})
2025-10-28 16:52:31 +08:00
}
} else {
if (this.fileUploadRule.fields_json) {
2025-10-28 17:26:06 +08:00
res = await uploadSmallFileByOcr(formData, {
signal: controller.signal
})
2025-10-28 16:52:31 +08:00
} else {
2025-10-28 17:26:06 +08:00
res = await uploadSmallFile(formData, {
signal: controller.signal
})
2025-10-28 16:52:31 +08:00
}
}
2025-10-28 17:26:06 +08:00
2025-10-28 16:52:31 +08:00
if (res.code === 200) {
2025-10-28 17:26:06 +08:00
this.handleSuccess(res, file)
2025-10-28 16:52:31 +08:00
} else {
2025-10-28 17:26:06 +08:00
this.handleError(new Error(res.message || '上传失败'), file)
2025-10-28 16:52:31 +08:00
}
} catch (err) {
2025-10-28 17:26:06 +08:00
if (err.name === 'AbortError') {
console.log('上传已取消:', file.name)
} else {
this.handleError(err, file)
}
2025-10-28 16:52:31 +08:00
} finally {
2025-10-28 17:26:06 +08:00
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,
2025-10-28 16:52:31 +08:00
}
},
findFileByRawFile(rawFile) {
return this.files.find(item =>
item.raw === rawFile ||
(item.name === rawFile.name && item.size === rawFile.size)
)
},
2025-10-28 17:26:06 +08:00
updateFileStatus(fileUid, status, statusText, responseData = null, percentage = null) {
const fileIndex = this.files.findIndex(item => item.uid === fileUid)
2025-10-28 16:52:31 +08:00
if (fileIndex !== -1) {
const updatedFile = {
...this.files[fileIndex],
status: status,
}
if (statusText) {
updatedFile.statusText = statusText
}
2025-10-28 17:26:06 +08:00
if (percentage !== null && percentage >= 0 && percentage <= 100) {
2025-10-28 16:52:31 +08:00
updatedFile.percentage = percentage
} else if (status === 'uploading') {
updatedFile.percentage = 0
} else if (status === 'success') {
updatedFile.percentage = 100
}
if (responseData) {
2025-10-28 17:26:06 +08:00
updatedFile.response = responseData
updatedFile.response.businessType = this.fileUploadRule?.fileUploadType
updatedFile.res = updatedFile.response
2025-10-28 16:52:31 +08:00
}
this.$set(this.files, fileIndex, updatedFile)
}
},
formatFileList(fileList) {
return fileList.map((file) => {
const formattedFile = {
uid: file.uid,
name: file.name,
size: file.size,
type: file.type,
status: file.status,
raw: file.raw,
}
if (file.percentage !== undefined && file.percentage !== null) {
2025-10-28 17:26:06 +08:00
formattedFile.percentage = Math.max(0, Math.min(100, file.percentage))
2025-10-28 16:52:31 +08:00
} else if (file.status === 'uploading') {
formattedFile.percentage = 0
} else if (file.status === 'success') {
formattedFile.percentage = 100
}
if (file.response) {
2025-10-28 17:26:06 +08:00
formattedFile.response = file.response
formattedFile.res = file.response
2025-10-28 16:52:31 +08:00
}
return formattedFile
})
},
getCurrentFiles() {
2025-10-28 17:26:06 +08:00
return this.files.map((file) => {
2025-10-28 16:52:31 +08:00
const fileObj = {
uid: file.uid,
name: file.name,
size: file.size,
type: file.type,
status: file.status,
}
if (file.raw) {
fileObj.raw = file.raw
}
if (file.response) {
fileObj.response = file.response
2025-10-28 17:26:06 +08:00
fileObj.response.businessType = this.fileUploadRule?.fileUploadType
2025-10-28 16:52:31 +08:00
}
return fileObj
})
},
},
}
</script>
2025-10-28 17:26:06 +08:00
2025-10-28 16:52:31 +08:00
<style scoped lang="scss">
.upload-container {
width: 100%;
.upload-demo {
width: 100%;
::v-deep .el-upload {
width: 100%;
.el-upload-dragger {
width: 100%;
2025-10-28 17:26:06 +08:00
height: 160px;
2025-10-28 16:52:31 +08:00
border: 2px dashed #dcdfe6;
border-radius: 8px;
background-color: #fafafa;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
&:hover {
border-color: #409eff;
background-color: #f5f7fa;
}
}
}
}
.upload-content {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
2025-10-28 17:26:06 +08:00
padding: 20px;
2025-10-28 16:52:31 +08:00
.upload-text {
text-align: center;
.main-text {
2025-10-28 17:26:06 +08:00
font-size: 16px;
2025-10-28 16:52:31 +08:00
color: #1f72ea;
2025-10-28 17:26:06 +08:00
margin-bottom: 8px;
2025-10-28 16:52:31 +08:00
font-weight: 500;
}
.tip-text {
font-size: 14px;
color: #909399;
2025-10-28 17:26:06 +08:00
line-height: 1.4;
2025-10-28 16:52:31 +08:00
div {
margin-bottom: 2px;
}
}
}
}
}
2025-10-28 17:26:06 +08:00
</style>