在utils里新建imageRatio.js
naturalWidth 支持ie9及以上
我用img.width获取不到,都是0,所以用naturalWidth
import {Message} from 'element-ui'
export function imageRatio(raw, ratio) {
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.readAsDataURL(raw)
reader.onload = () => {
let img = new Image()
img.src = reader.result
img.onload = () => {
if (img.naturalWidth / img.naturalHeight !== ratio) {
Message.error(`请上传${ratio}:1比例图片!`)
resolve(false)
} else {
resolve(true)
}
}
}
})
}
页面使用
<el-upload
id="uploadImg"
class="upload-demo"
action="string"
:show-file-list="false"
:on-change="UploadImage"
:auto-upload="false"
:accept="accept"
>
import {imageRatio} from '@/utils/imageRatio'
computed:{
accept() {
return 'jpeg,jpg';
}
}
UploadImage(file) {
let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1).toLowerCase()
let fileSize = file.size
let isImage = false
for (let mimeType of this.accept.split(',')) {
if (mimeType === testmsg) {
isImage = true
break
}
}
if (!isImage) {
this.$message.error('上传图片必须是JPG格式!')
return false
}
if (fileSize / 1024 / 1024 > 1) {
this.$message.error('上传图片大小不能超过 1MB!')
return false
}
imageRatio(file.raw, 1).then(async result => {
if (result) {
const formData = new FormData()
formData.append('image', file.raw)
let response = await UploadImage(formData)
}
}).catch(err => {
console.log(err)
})
},
网友评论