基于element upload的限定大小,比例的图片上传组件

2,841 阅读1分钟

需求,限制上传的图片大小和比例尺寸

1.html部分

<template>
<!-- 上传图片组件 -->
  <div>
    <el-upload
    class="avatar-uploader"
    action=""
    :http-request="uploadImage"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <div v-else class="prompt_box">
    <i class="el-icon-picture-outline"></i>
    <div class="prompt">设置封面</div>
    </div>
    <div class="el-upload__tip" slot="tip">图片比例为16:9,且不得超过2M,推荐格式png</div>
    </el-upload>
  </div>
</template>

2.js逻辑部分

<script>
import { imageUp } from '@/api/users' // 引入请求接口
export default {
  data () {
    return {
      imageUrl: '', // 图片地址
    }
  },
  methods: {
    // 图片上传前回调
    beforeAvatarUpload (file) {
      // 判断文件大小M为单位
      const fileSize = file.size / 1024 / 1024 < 2
      // 判断文件宽高比例
      const aaa = new Promise((resolve, reject) => {
        const url = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function () {
          // 图片比例校验
          console.log(img.width, img.height)
          const valid = img.width / img.height === 16 / 9
          // eslint-disable-next-line prefer-promise-reject-errors
          valid ? resolve() : reject()
        }
        img.src = url.createObjectURL(file)
      }).then(() => { return file }, () => {
        this.$message.error('图片比例不合格,请选择比例为16:9的图片')
        // eslint-disable-next-line prefer-promise-reject-errors
        return Promise.reject()
      })
      if (['image/png', 'image/jpeg', 'image/jpg'].indexOf(file.type) === -1) {
        this.$message.error('请上传正确的图片格式')
        return false
      }
      if (!fileSize) {
        this.$message.error('图片大小不能超过2MB')
      }
      return fileSize && aaa
    },
    // 上传图片
    async uploadImage (content) {
      // 构建formData对象
      const formData = new FormData()
      formData.append('fileName', content.file)
      const res = await imageUp(formData)
      if (res.code !== 200) return this.$message.error(res.messages)
      this.imageUrl = res.data.address
      // 讲文件id传出去
      this.$emit('getImgInfo', res.data.id)
    },
    // 上传成功时的回调
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    }
  }
}
</script>

3.样式部分

<style lang="less" scoped>
 /deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    width: 325px;
    height: 185px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 100%;
    height: 100%;
    display: block;
  }
  .prompt_box{
    width: 100%;
    height: 100%;
    background-color: #e2e2e2;
    position: relative;
    i{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      font-size: 60px;
      color: #afafaf;
    }
    .prompt{
      position: absolute;
      bottom: 0;
      width: 100%;
      height: 30px;
      background-color: #05b709;
      color: #ffffff;
      font-size: 16px;
      line-height: 30px;
    }
  }
  .el-upload__tip{
    margin-top: -12px;
    text-indent: 10px;
  }
</style>

4.组件使用

<uploadImg @getImgInfo='getImgInfo(arguments)'></uploadImg>

getImgInfo (val) {
   console.log(val) //接受图片信息
 }