實現Element的upload組件的圖片本地預覽
upload組件的html代碼如下:
<el-upload
class="avatar-uploader"
action=""
:show-file-list="false"
:before-upload="beforeAvatarUpload"
v-model="ruleForm.coverFile"
>
<img
v-if="ruleForm.coverUrl"
:src="ruleForm.coverUrl"
class="avatar"
/>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
在vue組件中的js代碼如下:
return {
ruleForm: {
coverUrl: "",
coverFile: ""
},
methods: {
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpeg";
const isPNG = file.type === "image/png";
const isLt1M = file.size / 1024 / 1024 < 1;
if (!isJPG && !isPNG) {
this.$message.error("上傳頭像圖片只能是 JPG 或 PNG 格式!");
} else if (!isLt1M) {
this.$message.error("上傳頭像圖片大小不能超過 1MB!");
} else {
this.ruleForm.coverFile = file;
this.imagePreview(this.ruleForm.coverFile);
}
// 不使用upload自帶的上傳方式,而是使用axios,所以阻止upload自帶的上傳
return false;
},
imagePreview: function(file) {
var self = this;
//定義一個文件閱讀器
var reader = new FileReader();
//文件裝載後將其顯示在圖片預覽裏
reader.onload = function(e) {
//將bade64位圖片保存至數組裏供上面圖片顯示
self.ruleForm.coverUrl = e.target.result;
};
reader.readAsDataURL(file);
}
}
}