需求:elementUI 框架上傳圖片诉濒,要判斷 圖片是否是 500*500 的尺寸
相關(guān)代碼:
html:
<el-form-item label="模板封面"
class="upload-img">
<el-upload class="el-upload-container avatar"
drag
action=""
element-loading-text="上傳中..."
:disabled="uploadLoadingAvatar"
accept="gif,jpg,jpeg,png"
:before-upload="handleBeforeUpload"
:http-request="handleUploadAvtar"
v-loading="uploadLoadingAvatar"
:show-file-list="false">
<div class="el-upload-area">
<img v-if="urls"
:src="urls"
style="width:200px;height:200px;">
<div v-show="!urls">
<i class="el-icon-upload"></i>
<p class="el-upload__text"><em>點(diǎn)擊上傳</em></p>
</div>
</div>
<p class="el-upload__tip"
slot="tip">500*500px,jpg/jepg/gif/png格式支持及志,20M以內(nèi)(點(diǎn)擊上圖上傳)</p>
</el-upload>
</el-form-item>
js:
// 上傳封面圖之前
handleBeforeUpload() {
if (!this.uploadStatus) {
this.$message.error('請等待其它視頻或圖片上傳完成')
}
},
// 上傳封面圖
handleUploadAvtar({ file }) {
if (!this.uploadStatus) {
this.urls = ''
return
}
if (file.size > 20 * 1024 * 1024) {
this.$message.error('圖片大小不能超過20M')
return
}
// eslint-disable-next-line no-new
new this.$upload({
fileData: file,
fileExt: ['gif', 'png', 'jpg', 'jpeg'],
onUploadBefore: () => {
this.uploadLoadingAvatar = true
this.uploadStatus = false
},
onSuccess: ({ url }) => {
const img = new Image()
img.src = url
// 需要賦值定義一下 this 值划纽,不然后面使用會有問題
const that = this
// 如果圖片被緩存锌畸,則直接返回緩存數(shù)據(jù)
if (img.complete) {
if (img.width !== 500 || img.height !== 500) {
that.$message.error('請上傳500*500px的圖片')
that.uploadLoadingAvatar = false
that.uploadStatus = true
} else {
// 賦值顯示相關(guān)圖片
that.urls = url
}
} else {
// 完全加載完畢的事件
img.onload = function() {
if (img.width !== 500 || img.height !== 500) {
that.$message.error('請上傳500*500px的圖片')
that.uploadLoadingAvatar = false
that.uploadStatus = true
} else {
that.urls = url
}
}
}
},
onComplete: () => {
this.uploadLoadingAvatar = false
this.uploadStatus = true
},
onTaskError: () => {
}
})
}
其中主要是 onSuccess 這段
const img = new Image()
img.src = url
// 需要賦值定義一下 this 值潭枣,不然后面使用會有問題
const that = this
// 如果圖片被緩存盆犁,則直接返回緩存數(shù)據(jù)
if (img.complete) {
if (img.width !== 500 || img.height !== 500) {
that.$message.error('請上傳500*500px的圖片')
that.uploadLoadingAvatar = false
that.uploadStatus = true
} else {
// 賦值顯示相關(guān)圖片
that.urls = url
}
} else {
// 完全加載完畢的事件
img.onload = function() {
if (img.width !== 500 || img.height !== 500) {
that.$message.error('請上傳500*500px的圖片')
that.uploadLoadingAvatar = false
that.uploadStatus = true
} else {
that.urls = url
}
}
}
要是有緩存數(shù)據(jù),就直接是 img.complete 的情況醋奠,要是 沒有,就要重新加載窜司,為 img.onload 的情況,在 之前 要進(jìn)行const that = this
的 賦值塞祈,不然后面使用會 模糊this 的指向報錯。
相關(guān)參考資料鏈接:https://www.jb51.net/article/149891.htm