此案例是区分上传的文件还是图片;
需要注意的是 before-upload
事件,如果是返回了 false,也会默认走on-remove
,需要在 remove事件里做file 的状态判断。
<template>
<el-upload class="upload-box" ref="uploadImgRef" :file-list="fileList" action="#"
:before-upload="onBeforeUploadImage"
:http-request="uploadAction" :auto-upload="true" :list-type="listType"
:on-remove="handleRmove"
:on-preview="handlePictureCardPreview">
<el-icon v-if="listType === 'picture-card'">
<Plus />
</el-icon>
<el-button v-else type="primary">选择文件</el-button>
</el-upload>
<el-dialog v-model="dialogVisible">
<img style="width: 100%" w-full :src="dialogImageUrl" />
</el-dialog>
</template>
<script>
import { uploadFile } from '@/api/common';
const PIC_TYPE = 'picture-card'; // 图片格式
export default {
props: {
listType: { // 已上传文件展示格式
type: String,
default: 'text'
},
fileList: { // 已上传文件列表
type: Array,
default: () => []
},
fileType: { // 上传文件的格式限制,以逗号分割的字符串,如图片:image/jpeg,image/jpg,image/png
type: String,
default: ''
}
// 如果还要限制上传的数量,也可匹配;上传之前先检查已有的数量,再进行上传;limit: 10
},
emits: ['changeFile'],
computed: {
uploadFileType () {
return this.listType === PIC_TYPE ? 'Img': 'File';
}
},
data () {
return {
dialogImageUrl: '',
dialogVisible: false,
uploadFileList: []
}
},
mounted () {
this.uploadFileList = [...this.fileList];
},
watch: {
fileList(val) {
this.uploadFileList = val
},
},
methods: {
handlePictureCardPreview (uploadFile) {
if (this.listType === PIC_TYPE) {
this.dialogImageUrl = uploadFile.url
this.dialogVisible = true
}
},
// 上传请求
async uploadAction (option) {
try {
console.log(option, 'option')
const res = await uploadFile({ file: option.file, fileType: this.uploadFileType });
const url = res.data.url;
const name = option.file.name;
this.uploadFileList.push({url, name});
this.$emit('changeFile', this.uploadFileType, [...this.uploadFileList]);
} catch (error) {
console.log(error)
}
},
onBeforeUploadImage (file) {
if (!this.fileType) return true;
const isRightType = this.isRightType(file.type);
if (!isRightType) {
this.$message.error(`上传文件格式错误! 请上传 ${this.fileType} 格式文件`)
}
return isRightType;
},
handleRmove (file, fileList) {
if (file.status == 'success') {
// 删除后改变某些状态的代码
console.log('remove =========');
const index = this.uploadFileList.findIndex((item) => item.uid === file.uid);
this.uploadFileList.splice(index, 1);
this.$emit('changeFile', this.uploadFileType, [...this.uploadFileList]);
}
if (file.status == 'ready') {
// 这里应该就是before-upload中返回false时的状况了,还有没有别的状况,未知
}
},
isRightType (type) {
let isRight = this.fileType.split(',').includes(type);
return isRight;
}
}
}
</script>
<style lang="scss" scoped>
.upload-box {
width: 100%;
}
</style>