ElementUI
ElementUI的上傳圖片元件非常簡單
只要像是這樣
<el-form-item label="圖片:" style="font-family:18px">
<el-upload
action
accept="image/jpeg, image/png"
:on-change="onUploadChange"
:before-remove="onUploadRemove"
:auto-upload="false"
:show-file-list="true"
:file-list="fileList"
>
<el-button size="small" type="primary">選擇圖片</el-button>
</el-upload>
</el-form-item>
然後可以在圖片上傳後檢查是否符合需求
onUploadChange: async function(file) {
const isIMAGE =
file.raw.type === "image/jpeg" || file.raw.type === "image/png";//判別格式
const isLt1M = file.size / 1024 / 1024 < 500000;//判別大小
if (!isIMAGE) {
this.$message.error("只能上傳jpg,png格式");
return false;
}
if (!isLt1M) {
this.$message.error("上傳圖片大小不能大於5MB");
return false;
}
this.picBase64 = await setBase64(file); //這邊將base64存入變數(setBase64()額外實作)
}
另外記得如果把圖片刪除時也要一併刪除變數內數值
onUploadRemove: async function() {
this.picBase64 = null;
}