以下内容是引用或者借鉴别人的,自己只是做个笔记,方便学习。理解错误的地方,欢迎评论。如有侵权,私聊我删除,未经允许,不准作为商业用途
当是单个图片上传时,beforeUpload
函数中返回的file
里面没有图片的宽度和高度,所以将调用URL.createObjectURL()
方法生成预览图片路径,加载图片,读取宽度和高度。点击在线运行,效果如图
image.png
- 切记在
onload
方法中直接return false
是无法阻止验证通过的,因为只会返回当前函数层,外层函数无法接收到 - 因此引入
Promise
,通过reject
,停止上传
<template>
<div id="app">
<el-upload
:action="actionUrl"
:show-file-list="false"
:before-upload="beforeUpload"
:on-success="handleSuccess"
accept="image/*"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">图片尺寸只支持900px*383px(请上传png图片)</div>
<img v-show="imgUrl" :src="imgUrl" width="300" />
</el-upload>
</div>
</template>
<script>
export default {
name: "App",
components: {},
data() {
return {
actionUrl: "https://jsonplaceholder.typicode.com/posts/", //正式环境上传地址
imgUrl: ""
};
},
mounted() {},
methods: {
beforeUpload(file) {
console.log(file);
let result = new Promise((resolve, reject) => {
const ff = file.name;
if (!/.(gif|jpg|jpeg|png|gif|jpg|png)$/gi.test(ff)) {
this.$message.warning("封面图片只能是图片");
reject();
} else {
var img_src = URL.createObjectURL(file);
var img_temp = new Image();
img_temp.src = img_src;
img_temp.onload = () => {
if (img_temp.width == 900 && img_temp.height == 383) {
resolve(true);
} else {
this.$message.warning("图片尺寸只支持900px*383px");
reject(false);
}
};
}
});
return result;
},
handleSuccess(res) {
console.log(res);
// this.imgUrl = res.datas && res.datas.url; //正式环境返回的url
this.imgUrl =
"https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg";
}
}
};
</script>
网友评论