前言
总要写点东西吧,最近忙于项目,github上的问题也没处理,博客也没咋写,自媒体上的东西也没咋发,随手记录一下当前项目改造时候遇到的问题吧;
upload
: https://element.eleme.cn/#/zh-CN/component/upload
内容
before-upload
代码语言:javascript复制借助于
:before-upload
来进行校验,使用FileReader
和Image
来获取图片宽高,为了让代码更通用,我们可以进行以下的封装;
getImageSize(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = e => {
const image = new Image()
image.onload = () => {
resolve({
width: image.width,
height: image.height
})
}
image.src = e.target.result
}
reader.readAsDataURL(file)
})
},
伪代码
代码语言:javascript复制<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:before-upload="beforeProductImageUpload"
:on-remove="handleRemove">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<script>
export default {
data() {
return {
dialogImageUrl: '',
dialogVisible: false
};
},
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
beforeProductImageUpload(file) {
const imgType = ['image/png', 'image/jpeg', 'image/jpg'].includes(file.type)
if (!imgType) {
this.$message.warning('产品主图只允许JPG/PNG/JPEG格式')
return false
}
return this.getImageSize(file).then(size => {
if (size.width !== 108 && size.height !== 108) {
this.$message.warning('产品主图尺寸必须为108*108')
return Promise.reject()
}
})
},
}
}
</script>
Tips
代码语言:javascript复制为了回显一般都会增加
file-list
,不过这个会导致上传时前后部分数据不一致,触发闪动,所以这里直接把相应的css效果干掉
:deep(.el-upload-list__item.is-ready) {
display: none;
}