使用Elementui框架,按需引入update上传组件,按照官网引用即可。
上代码。。。
<template>
<el-form-item v-show="blockpuzzle && huoti" label="配置手厅背景图片" label-width="160px" prop="shouimgSrc">
<el-upload
class="centerImg"
name="upfile1" //给上传的图片添加名字
:class="{hide:hideUploadIcon1}" //控制图片达到上传个数后上传入口隐藏
:action="'后端给的上传图片地址'" // 上传地址
list-type="picture-card" //文件列表的类型
:on-preview="handlePictureCardPreview1" //点击文件列表中已上传的文件时的钩子
:on-success="onSuccess1" //上传成功调用的函数
:on-remove="handleRemoveIcon1" //删除上传文件时调用的函数
:auto-upload="true" //为true是选去立即上传,为false时可以手动上传设置
:limit="1" //限制上传的图片数量
:before-upload="beforeAvatarUpload1" //上传文件之前的钩子,可以添加对上传图片的限制
ref="uploadicon"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible1">
<img width="100%" :src="dialogImageUrl1" alt="">
</el-dialog>
<!-- <el-button @click="iconDialogVisible = false">取 消</el-button> -->
<!-- <el-button type="primary" @click="saveIco()" >提 交</el-button> -->
</el-form-item>
<template>
export default {
data(){
ruleForm:{
shouimgSrc:''
},
dialogImageUrl1:'',
dialogVisible1:'',
hideUploadIcon1:''
...
},
methods:{
beforeAvatarUpload1(file) {//文件上传之前调用做一些拦截限制
let isLt2M = file.size / 1024 < 50;
//格式限制
var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
let extension = testmsg === 'png'
let extension2 = testmsg === 'jpg'
if(!extension && !extension2) {
this.$message({
message: 'icon 图只能是 png / jpg 格式!',
type: 'warning'
});
return false;//必须加上return false; 才能阻止
}
// 大小限制
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 50KB!');
}
// 宽高限制
let isSize = new Promise(function(resolve, reject){
let width = 565;
let height = 240;
let _URL = window.URL || window.webkitURL;
let img = new Image();
img.onload = function(){
let valid = img.width == width && img.height == height;
valid ? resolve() : reject();
}
img.src = _URL.createObjectURL(file);
}).then(()=>{
return file;
}, ()=>{
this.$message({
message:'图片尺寸只能是565*240px!请重新选择!',
type: 'warning'
});
return Promise.reject()
return false;//必须加上return false; 才能阻止
})
return isLt2M && isSize;
},
handlePictureCardPreview1(file) {
this.dialogImageUrl1 = file.url;
this.dialogVisible1 = true;
},
handleRemoveIcon1(file,fileList){
// console.log(file)
this.ruleForm.shouimgSrc = '' // 清空储存地址
this.hideUploadIcon1 = false
},
onSuccess1(file){
this.ruleForm.shouimgSrc = file.filePath //储存地址
this.hideUploadIcon1 = true
console.log(file)
},
}
}
在此记录该问题,如有错误,望大佬们指正。