直接上代码:
<template>
<el-upload
accept=".jpg,.png,.bmp"
action="https://up-z0.qiniup.com"
list-type="picture-card"
:data="qiniuData"
:on-success="onSuccess"
:before-upload="beforeUpload"
:on-remove="handleRemove"
:file-list="fileList"
ref="files">
<i slot="default" class="el-icon-plus"></i>
</el-upload>
</template>
<script>
import uploadApi from '@/api/upload'
export default {
data(){
return {
qiniuData:{
key:'',
token:''
},
fileList:[]
}
},
created(){
//获取七牛云token
uploadApi.getToken().then(res => {
this.qiniuData.token = res.data
})
},
methods: {
beforeUpload(file) {
let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
this.qiniuData.key = new Date().getTime(); // key为上传后文件名 必填
const extension =
testmsg === "jpg" ||
testmsg === "JPG" ||
testmsg === "png" ||
testmsg === "PNG" ||
testmsg === "bmp" ||
testmsg === "BMP";
const isLt50M = file.size / 1024 / 1024 < 10;
if (!extension) {
this.$message({
message: "上传图片只能是jpg / png / bmp格式!",
type: "error",
});
return false; //必须加上return false; 才能阻止
}
console.log(file);
if (!isLt50M) {
this.$message({
message: "上传文件大小不能超过 10MB!",
type: "error",
});
return false;
}
return extension || isLt50M;
},
// 图片上传成功
onSuccess(res, file) {
this.orgFormData.icon = `https://域名/${res.key}`
},
handleRemove(e) {
this.fileList=[]
},
add(){
this.fileList = []
},
edit(id){
//编辑时回显
this.$nextTick(()=>{
this.$refs.files.clearFiles()
this.fileList = []
})
this.fileList.push( { url:'这里填已经上传的图片url进行回显' } )
}
}
}
</script>