vue 文件上传判断文件尺寸级大小
一、vue 基于elementui实现文件或图片上传判断文件或图片的尺寸;本例基于图片上传的demo
<el-form-item label="添加图片"> <div class="imgList"> <div class="imgBox" :class="{pitch:item.alter}" v-for="(item,indexs) in imageArr" :key="indexs" @mousemove="moveImg(item)" @mouseout="outImg(item)"> <img class="img" :preview="indexs" :src="item.url"/> <img v-if="item.alter" @click="deleteImg(indexs)" class="deleteImg"src="../../assets/img/deleteImg.png"/> </div> <el-upload multiple class="avatar-uploader" :action="action" accept="image/*" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <i v-if="imageArr.length<1" class="el-icon-plus avatar-uploader-icon"></i> </el-upload> <div class="el-upload__tip" slot="tip">banner尺寸为750*388px , 支持jpg/png格式,不超过5M</div> </div>
</el-form-item>
export default { data(){ return { picture:[], picname:[], imageArr:[], } }, methods:{ handleAvatarSuccess(res, file) { this.picture.push(res.data); this.picname.push(res.fileName); this.imageArr.push({url: URL.createObjectURL(file.raw), alter: false}); }, beforeAvatarUpload(file) { const isLt5M = file.size / 1024 / 1024 < 5; const isJPG = checkImg(file.name); if (!isLt5M) { this.$message.error('上传图片大小不能超过5MB!'); } if(!isJPG){ this.$message.error('上传图片格式是jpg/jpeg/png!'); }
//核心代码部分 const isSize = new Promise(function(resolve, reject) { let width = 750; let height = 388; let _URL = window.URL || window.webkitURL; let img = new Image(); img.onload = function() { let valid = img.width == width && img.height == height; valid ? resolve() : reject(); } img.src = _URL.createObjectURL(file); }).then(() => { return file; }, () => { this.$message.error('banner尺寸必须是750*388!'); return Promise.reject(); }); return isLt5M && isJPG && isSize; }, moveImg(item){ item.alter = true; }, outImg(item){ item.alter = false; }, deleteImg(index){ this.$confirm('您确定要删除作品图片吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => { this.imageArr.splice(index,1); this.picture.splice(index,1); }).catch(() => { }); }, } }
其中 checkImg()方法是判断图片的格式,通过这种方式可判断出上传图片的尺寸及大小!