vue实战

vue+elementui实现图片上传尺寸、大小限制

2022-12-10 13:50:01 更新   浏览量: 89
上一章:Vue实现随机数猜数字1-10之间小游戏 本章完

学习其他章节 vue实战案例

vue+elementui实现图片上传尺寸、大小限制,尺寸限制为500 x 300,单位是px ; 大小是2M;  代码如下实例显示:

实例

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> vue+elementui实现图片上传尺寸、大小限制  -(qianduan.cn)</title>
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- import Vue before Element -->
<script src="https://www.qianduan.cn/static/js/vue.min.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
 <el-upload
  class="avatar-uploader"
  action="https://jsonplaceholder.typicode.com/posts/"
  accept="image/jpg,image/jpeg,image/png"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="handleBeforeUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

</div>
<script>
new Vue({
el: '#app',
data: function () {
return {
 imageUrl: ''
 }
},
methods: {
// 限制图片尺寸
limitFileWH(E_width, E_height, file) {
const _this = this
let imgWidth = ''
let imgHight = ''
const isSize = new Promise(function(resolve, reject) {
const width = E_width
const height = E_height
const _URL = window.URL || window.webkitURL
const img = new Image()
img.onload = function() {
imgWidth = img.width
imgHight = img.height
const valid = img.width === width && img.height === height
valid ? resolve() : reject()
}
img.src = _URL.createObjectURL(file)
}).then(() => {
return true
}, () => {
_this.$message.warning({
message: '上传图片的尺寸应为' + E_width + '*' + E_height + ',当前上传图片的尺寸为:' + imgWidth + '*' + imgHight,
btn: false
})
return false
})
return isSize
},
// 图片上传之前的判断
handleBeforeUpload(file) {
return new Promise((resolve, reject) => {
const suffix = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
const isLt1M = file.size / 1024 / 1024 < 2
if (!suffix) {
this.$message.error('只能上传图片!')
return reject(false)
}
if (!isLt1M) {
this.$message.error('上传图片大小不能超过 2MB!')
return reject(false)
}
// 调用[限制图片尺寸]函数
this.limitFileWH(500, 300, file).then((res) => {
file.isFlag = res
if (file.isFlag) {
return resolve(true)
} else {
return reject(false)
}
})
})
},
// 上传成功的回调
handleAvatarSuccess(res, file) {
// 通过URL.createObjectURL(blob)可以获取当前文件的一个内存URL
this.imageUrl = URL.createObjectURL(file.raw);
}

}
})
</script>
</body>
</html>

运行预览 »

运行效果如下:


扫二微码
上一章:Vue实现随机数猜数字1-10之间小游戏 本章完
学习其他章节 vue实战案例

最近更新 免责声明 关于我们

Copyright © 2004-2021 前端教程 qianduan.cn All Rights Reserved   陕ICP备2021014585号-1 陕公网安备 61012402000223号 前端教程

友情链接:  前端工具 前端插件