以下內(nèi)容是引用或者借鑒別人的,自己只是做個(gè)筆記旷痕,方便學(xué)習(xí)碳锈。理解錯(cuò)誤的地方,歡迎評(píng)論欺抗。如有侵權(quán)售碳,私聊我刪除,未經(jīng)允許绞呈,不準(zhǔn)作為商業(yè)用途
當(dāng)是單個(gè)圖片上傳時(shí)贸人,beforeUpload
函數(shù)中返回的file
里面沒有圖片的寬度和高度,所以將調(diào)用URL.createObjectURL()
方法生成預(yù)覽圖片路徑报强,加載圖片灸姊,讀取寬度和高度。點(diǎn)擊在線運(yùn)行秉溉,效果如圖
image.png
- 切記在
onload
方法中直接return false
是無(wú)法阻止驗(yàn)證通過的力惯,因?yàn)橹粫?huì)返回當(dāng)前函數(shù)層碗誉,外層函數(shù)無(wú)法接收到 - 因此引入
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">點(diǎn)擊上傳</el-button>
<div slot="tip" class="el-upload__tip">圖片尺寸只支持900px*383px(請(qǐng)上傳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/", //正式環(huán)境上傳地址
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; //正式環(huán)境返回的url
this.imgUrl =
"https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg";
}
}
};
</script>