单文件上传优化

This commit is contained in:
cwchen 2025-10-28 17:32:57 +08:00
parent 2f8541ea17
commit b3729efd6f
1 changed files with 258 additions and 354 deletions

View File

@ -1,11 +1,24 @@
<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">
<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"
>
<div class="upload-content">
<!-- 当只有一张图片时显示缩略图 -->
<!-- 图片预览 -->
<div v-if="showImagePreview" class="image-preview">
<img :src="previewImageUrl" :alt="previewImageName" class="preview-thumbnail" />
<div class="preview-overlay">
@ -16,10 +29,10 @@
</div>
</div>
<!-- 当只有一个文档文件时显示文件图标 -->
<!-- 文档预览 -->
<div v-else-if="showFilePreview" class="file-preview">
<div class="file-icon-container">
<i :class="getFileIconClass()" class="file-icon"></i>
<i :class="fileIconClass" class="file-icon"></i>
<div class="file-name">{{ previewFileName }}</div>
</div>
<div class="preview-overlay">
@ -50,6 +63,30 @@ import {
uploadSmallFile,
uploadLargeFile,
} from '@/api/common/uploadFile.js'
//
const FILE_STATUS = {
READY: 'ready',
UPLOADING: 'uploading',
SUCCESS: 'success',
FAIL: 'fail',
REMOVED: 'removed'
}
const FILE_TYPES = {
IMAGE: '1',
DOCUMENT: '2'
}
const DEFAULT_FILE_SIZE = 5 * 1024 * 1024 // 5MB
const ICON_MAP = {
pdf: 'el-icon-document',
doc: 'el-icon-document',
docx: 'el-icon-document',
xls: 'el-icon-document',
xlsx: 'el-icon-document',
}
export default {
name: 'UploadFile',
props: {
@ -89,47 +126,29 @@ export default {
previewImageName: '',
previewFileName: '',
previewFileType: '',
isUploading: false, //
defaultFileSize: 1024 * 1024 * 5, // 5MB 5MB
skipNextChange: false,
isUploading: false,
}
},
computed: {
//
showImagePreview() {
return this.previewImageUrl && this.files.length === 1
},
//
showFilePreview() {
return (
this.previewFileName &&
this.previewFileType &&
this.files.length === 1
)
return this.previewFileName && this.previewFileType && this.files.length === 1
},
accept() {
return this.uploadType
.split('、')
.map((type) => `.${type}`)
.join(',')
return this.allowedTypes.map(type => `.${type}`).join(',')
},
//
allowedTypes() {
return this.uploadType.split('、')
},
// MB
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
}
if (sizeStr.includes('mb')) return parseFloat(sizeStr)
if (sizeStr.includes('kb')) return parseFloat(sizeStr) / 1024
if (sizeStr.includes('gb')) return parseFloat(sizeStr) * 1024
return 20
},
// MIME
mimeTypes() {
const typeMap = {
png: 'image/png',
@ -141,21 +160,18 @@ export default {
xls: 'application/vnd.ms-excel',
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}
return this.allowedTypes.map((type) => typeMap[type] || '')
return this.allowedTypes.map(type => typeMap[type] || '')
},
fileIconClass() {
return ICON_MAP[this.previewFileType] || 'el-icon-document'
}
},
watch: {
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)
})
}
@ -165,21 +181,16 @@ export default {
},
},
methods: {
//
beforeUpload(file) {
//
if (this.isUploading) {
this.$message.warning('当前有文件正在上传,请稍后再试')
return false
}
//
const fileExtension = file.name.split('.').pop().toLowerCase()
const fileExtension = this.getFileExtension(file.name)
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) {
@ -194,271 +205,180 @@ export default {
return true
},
//
//
handleFileChange(file, fileList) {
//
if (file.status === 'removed' || file.status === 'fail' || file.status === 'success') {
console.log('现在的文件:', this.files);
return
}
//
if (this.shouldIgnoreFileChange(file.status)) 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)
this.updatePreview(fileList)
},
//
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]
const newFileObj = this.createFileObject(newFile)
this.files = [newFileObj]
this.updatePreview([newFileObj])
//
if (this.autoUpload && !this.isUploading) {
this.$nextTick(() => {
this.$refs.upload.submit()
})
}
} else {
//
this.clearPreview()
}
},
//
//
handleRemove(file, fileList) {
if (!file) {
this.clearPreview()
return true
}
if (this.isUploading && file.status === FILE_STATUS.UPLOADING) {
this.$message.warning('文件正在上传中,请稍后再删除')
return false
}
this.updatePreview(fileList)
this.files = this.formatFileList(fileList)
const delFileObj = this.findFileByRawFile(file.raw)
if (delFileObj) {
delFileObj.response = delFileObj.res
this.$emit('del-file', delFileObj)
}
this.$emit('file-change', this.getCurrentFiles(), this.type)
return true
},
//
async customUpload(options) {
const { file } = options
this.isUploading = true
const uploadFileObj = this.findFileByRawFile(file)
if (!uploadFileObj) {
this.handleError(new Error('文件对象不存在'), file)
return
}
const fileUid = uploadFileObj.uid
const statusText = this.fileUploadRule.fields_json ? '识别中' : '上传中'
this.updateFileStatus(fileUid, FILE_STATUS.UPLOADING, statusText, null, 0)
this.$bus.$emit('startUpload', statusText)
try {
const formData = this.createFormData(file)
const res = await this.uploadFile(formData, file.size)
if (res.code === 200) {
this.handleSuccess(res, uploadFileObj)
} else {
this.handleError(new Error(res.message || '上传失败'), uploadFileObj)
}
} catch (err) {
this.handleError(err, uploadFileObj)
} finally {
this.isUploading = false
}
},
//
handleSuccess(response, file) {
this.$bus.$emit('endUpload')
//
this.updateFileStatus(file.uid, 'success', '', response.data, 100)
//
this.updateFileStatus(file.uid, FILE_STATUS.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));
//
getFileExtension(filename) {
return filename.split('.').pop().toLowerCase()
},
// el-upload
const uploadFileObj = this.findFileByRawFile(file);
if (!uploadFileObj) {
console.error('未找到对应的文件对象');
this.handleError(new Error('文件对象不存在'), file);
return;
}
shouldIgnoreFileChange(status) {
return [FILE_STATUS.REMOVED, FILE_STATUS.FAIL, FILE_STATUS.SUCCESS].includes(status)
},
const fileUid = uploadFileObj.uid;
createFormData(file) {
const formData = new FormData()
formData.append('file', file)
formData.append('params', JSON.stringify(this.fileUploadRule))
return formData
},
// 0
this.updateFileStatus(
fileUid,
'uploading',
this.fileUploadRule.fields_json ? '识别中' : '上传中',
null,
0,
);
async uploadFile(formData, fileSize) {
const isLargeFile = fileSize > DEFAULT_FILE_SIZE
const hasOcr = !!this.fileUploadRule.fields_json
try {
this.$bus.$emit(
'startUpload',
this.fileUploadRule.fields_json ? '识别中' : '上传中',
);
let res = null;
if (this.defaultFileSize < file.size) {
if (this.fileUploadRule.fields_json) {
res = await uploadLargeFileByOcr(formData);
if (isLargeFile) {
return hasOcr ? await uploadLargeFileByOcr(formData) : await uploadLargeFile(formData)
} else {
res = await uploadLargeFile(formData);
}
} else {
if (this.fileUploadRule.fields_json) {
res = await uploadSmallFileByOcr(formData);
} else {
res = await uploadSmallFile(formData);
}
}
if (res.code === 200) {
this.handleSuccess(res, uploadFileObj);
} else {
this.handleError(new Error(res.message || '上传失败'), uploadFileObj);
}
} catch (err) {
this.handleError(err, uploadFileObj);
} finally {
//
this.isUploading = false;
return hasOcr ? await uploadSmallFileByOcr(formData) : await uploadSmallFile(formData)
}
},
//
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,
)
},
removeFailedFile(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,
)
if (fileIndex !== -1) {
const updatedFile = {
...this.files[fileIndex],
status: status,
updateFileStatus(fileUid, status, statusText = null, responseData = null, percentage = null) {
const fileIndex = this.files.findIndex(item => item.uid === fileUid)
if (fileIndex === -1) {
console.warn('未找到要更新的文件:', fileUid)
return
}
if (statusText) {
updatedFile.statusText = statusText
}
const updatedFile = { ...this.files[fileIndex], status }
// percentage 0-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 (statusText) updatedFile.statusText = statusText
if (percentage !== null) updatedFile.percentage = Math.max(0, Math.min(100, percentage))
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) => {
//
return fileList.map(file => {
const formattedFile = {
uid: file.uid,
name: file.name,
@ -468,164 +388,148 @@ export default {
raw: file.raw,
}
// percentage
//
if (file.percentage !== undefined && file.percentage !== null) {
formattedFile.percentage = Math.max(
0,
Math.min(100, file.percentage),
)
} else if (file.status === 'uploading') {
formattedFile.percentage = Math.max(0, Math.min(100, file.percentage))
} else if (file.status === FILE_STATUS.UPLOADING) {
formattedFile.percentage = 0
} else if (file.status === 'success') {
} else if (file.status === 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
}
if (file.filePath) formattedFile.filePath = file.filePath
if (file.statusText) formattedFile.statusText = file.statusText
return formattedFile
})
},
//
getCurrentFiles() {
const currentFiles = this.files.map((file) => {
return this.files.map(file => {
const fileObj = {
uid: file.uid,
name: file.name,
size: file.size,
type: file.type,
status: file.status,
percentage: file.percentage || 0,
}
// percentage
if (file.percentage !== undefined) {
fileObj.percentage = file.percentage
}
//
if (file.raw) {
fileObj.raw = file.raw
}
//
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
},
createFileObject(file) {
return {
name: file.name,
size: file.size,
type: file.type,
raw: file,
uid: Date.now(),
status: FILE_STATUS.READY,
percentage: 0,
}
},
//
//
isImageFile(file) {
return (
(file && file.type && file.type.startsWith('image/')) ||
(file && file.fileType === '1')
)
return (file && file.type && file.type.startsWith('image/')) || (file && file.fileType === FILE_TYPES.IMAGE)
},
//
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')
)
const fileExtension = this.getFileExtension(file.name)
return ['pdf', 'doc', 'docx', 'xls', 'xlsx'].includes(fileExtension) ||
(file && file.fileType === FILE_TYPES.DOCUMENT)
},
//
updatePreview(fileList) {
if (fileList.length === 0) {
this.clearPreview()
return
}
if (fileList.length === 1 && fileList[0]) {
const file = fileList[0].raw || fileList[0]
if (this.isImageFile(file)) {
fileList[0].lsFilePath ?
this.generateImagePreviewFromPath(fileList[0]) :
this.generateImagePreview(file)
} else if (this.isDocumentFile(file)) {
this.generateDocumentPreview(file)
}
} else {
this.clearPreview()
}
},
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.previewFileType = this.getFileExtension(file.name)
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',
handlePreviewFromExternal(fileList) {
if (fileList.length > 0) {
const firstFile = fileList[0]
if (firstFile?.lsFilePath) {
this.isImageFile(firstFile) ?
this.generateImagePreviewFromPath(firstFile) :
this.generateDocumentPreview(firstFile)
} else if (firstFile?.raw) {
this.isImageFile(firstFile.raw) ?
this.generateImagePreview(firstFile.raw) :
this.generateDocumentPreview(firstFile.raw)
} else {
this.clearPreview()
}
} else {
this.clearPreview()
}
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>