美文网首页
element-ui上传图片限制图片比例

element-ui上传图片限制图片比例

作者: w_小伍 | 来源:发表于2020-10-10 17:33 被阅读0次

    在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)
            })
          },
    

    相关文章

      网友评论

          本文标题:element-ui上传图片限制图片比例

          本文链接:https://www.haomeiwen.com/subject/erejpktx.html