背景
vue+element后台管理系统中的表单提交包含“资质上传”功能(就是需要多图片上传)
要求:
- 文件上传之前做处理
限制最多只能上传10张图片
格式限制 ‘image/jpeg’, ‘image/png’, ‘image/jpg’
图片不能超过2MB
上传图片的宽高限制为宽:750,高:500
实现代码:
HTML
说明:
action 必选参数,上传的地址 string
list-type 文件列表的类型 string text/picture/picture-card
file-list 上传的文件列表 array
on-remove 文件列表移除文件时的钩子 function(file, fileList)
before-upload 上传文件之前的钩子 function(file)
headers 设置上传的请求头部 object
on-success 文件上传成功时的钩子 function(response, file, fileList)
on-error 文件上传失败时的钩子 function(err, file, fileList)
on-exceed 文件超出个数限制时的钩子 function(files, fileList)
on-progress 文件上传时的钩子 function(event, file, fileList)
http-request 覆盖默认的上传行为,可以自定义上传的实现 function
<template>
<div>
<el-upload
:action="actionSrc"
list-type="picture-card"
:file-list="files"
:on-remove="handleRemove"
:before-upload="beforeAvatarUpload"
:headers="headerObj"
:on-success="successFn"
:on-error="errorFn"
:on-exceed="exceedLength"
:on-progress="uploadVideoProcess"
style="border: 1px solid #DCDFE6;border-radius: 4px;padding: 10px;"
>
<i class="el-icon-plus" />
<div slot="tip" class="el-upload__tip" style="color: #E6A23C;"> 请上传相关资质图片,最多上传10张。</div>
<div slot="tip" class="el-upload__tip" style="color: #E6A23C;"> 仅支持上传jpg/png/jpeg格式文件,单个图片大小不超过500kb。</div>
</el-upload>
</div>
</template>
JS
思路:
添加或编辑保存时 每次图片上传成功后 后台会返回一个id 把所有id组成字符串用逗号隔开进行赋值。
列表页点击编辑进行回显图片。
说明:
showFn() 方法用来回显后台返回的图片,
添加的时候需要清空数据
编辑的时候获取回显数据
watch 监听 回显图片的数据如果有改变 需要更新回显数据
<script>
import store from '@/store'
export default {
props: {
fileSrc: {
type: Array,
default: () => []
},
fileId: {
type: String,
default: ''
},
watchFlag: {
type: String,
default: ''
}
},
data() {
return {
files: [],
loadProgress: 0, // 动态显示进度条
progressFlag: false, // 关闭进度条
dialogImageUrl: '',
dialogVisible: false,
srcArray: [],
headerObj: {
Authorization: store.getters.token
},
actionSrc: process.env.VUE_APP_BASE_API + '/common-server/common/upload'
}
},
watch: {
watchFlag: {
handler(newValue, oldValue) {
for (let i = 0; i < newValue.length; i++) {
if (oldValue[i] !== newValue[i]) {
// console.log('我是:watch')
this.showFn()
}
}
},
deep: true
}
},
mounted() {
// console.log('我是:mounted')
},
created() {
// console.log('我是:created')
this.showFn()
},
methods: {
// 回显
showFn() {
if (this.fileId !== '') { // 编辑
var fileIdArray = this.fileId.split(',')
// 回显图片
this.files = fileIdArray.map((t, index) => {
var obj = {}
obj.url = this.fileSrc[index]
obj.uid = t
return obj
})
// 编辑的时候需要加上原来的图片id
this.srcArray = []
this.srcArray = this.srcArray.concat(fileIdArray)
} else { // 添加
this.files = []
this.srcArray = []
}
},
// 删除
handleRemove(file, fileList) {
var delId = file.uid
if (file.response !== undefined) {
delId = file.response.result.id
}
// 删除图片的同时删除提交的图片ID
this.srcArray.forEach((e, i) => {
if (e.indexOf(delId) !== -1) {
this.srcArray.splice(i, 1)
}
})
console.log(file, fileList)
console.log(this.srcArray, '删除')
this.$emit('setFileId', this.srcArray.join())
},
// 请求报错
errorFn(err, file, fileList) {
console.log(err, file, fileList, 'shibai')
this.$message.error('上传失败!')
},
// 请求成功
successFn(res, file, fileList) {
console.log(file, fileList, '添加')
this.srcArray.push(res.result.id)
console.log(this.srcArray)
this.$emit('setFileId', this.srcArray.join())
},
// 进度条
uploadVideoProcess(event, file, fileList) {
this.loadProgress = parseInt(event.percent) // 动态获取文件上传进度
if (this.loadProgress >= 100) {
this.loadProgress = 100
// setTimeout(() => { this.progressFlag = false }, 1000) // 一秒后关闭进度条
}
},
// 文件上传之前做处理
beforeAvatarUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 2
if (this.srcArray.length >= 10) {
this.$message.error('最多只能上传10张图片!')
return false
}
if (['image/jpeg', 'image/png', 'image/jpg'].indexOf(file.type) === -1) {
this.$message.error('上传图片格式不正确!')
return false
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!')
return false
}
const isSize = new Promise(function(resolve, reject) {
const width = 750
const height = 500
const _URL = window.URL || window.webkitURL
const img = new Image()
img.onload = function() {
const valid = img.width <= width && img.height <= height
valid ? resolve() : reject()
}
img.src = _URL.createObjectURL(file)
}).then(() => {
// 调用上传接口
}, () => {
this.$message.error('上传的图片最大尺寸为750*500!')
return Promise.reject()
})
return isSize
},
exceedLength() {
this.$message.error('最多只能上传10张图片!')
return false
}
}
}
</script>
CSS
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
父级调用
代码片段
<more-picture :file-src="qualificationUrls" :file-id="ruleForm.qualificationIds" :watch-flag="watchFlag" @setFileId="getFileArray($event)" />
import morePicture from '@/components/uploadMorePicture'
components: {
morePicture
},
工作之余 用博客记录自己 希望有能帮助到各位看官
如有错误或不全面的地方望各位能提点一二和留下宝贵意见