index.vue 10 KB
<template>
  <div class="upload-ctnr">
    <label v-if="name" class="label" for="">{{name}}</label>
    <div class="img-item"  :style="defaultStyle">
      <div v-if="!formObj[attr]" :class="['add-img',{'disabled': disabled}]" @click.stop="addFile">
        <input type="file" class="file" id="file" ref="fileRef" @change="handleFileChange" :accept="accept" />
        <i class="el-icon-plus add"></i>
        <p>{{ btnName }}</p>
      </div>
      <template v-if="formObj[attr] && isImage(formObj[attr])">
        <img class="image" :src="formObj[attr]" alt="" />
        <div class="operate">
          <div class="btn-wrap">
            <i class="el-icon-edit-outline" @click.stop="edit" v-if="isEdit"></i>
            <i class="el-icon-view"  @click.stop="handleLook('img')" v-else></i>
            <i class="el-icon-delete" @click.stop="del"></i>
          </div>
        </div>
      </template>
      <div v-if="formObj[attr] && !isImage(formObj[attr])" class="video-panel">
        <video id="video" width="100%" height="100%" preload loop muted>
          <source :src="formObj[attr]" type="video/mp4" />
        </video>
        <i class="el-icon-video-play" @click.stop="handleLook('video')"></i>
        <i class="el-icon-close" @click.stop="del"></i>
      </div>
    </div>
    <span v-if="tip" :class="['tip', {'tip-bottom': placement=='bottom'}]">{{ tip }}</span>
    <el-dialog append-to-body class="image-dialog" :visible.sync="dialogVisibleImg" width="30%">
      <big-view ref="viewForm" v-if="dialogVisibleImg" :dialogSrc="formObj[attr]" :dialogType="dialogType"></big-view>
    </el-dialog>
  </div>
</template>
  
<script>
import upload from '@/api/uploadApi'
import util from '@/utils/util'
import bigView from '@/components/big-view'
import uploadMixin from '@/mixins/upload'
export default {
    name: 'Upload',
    mixins: [uploadMixin],
    components: {
      bigView
    },
    props: {
      disabled: {
        type: Boolean,
        default: false
      },
      fileType: {
        type: String,
        default: 'image'
      },
      empty: {
        type: Boolean,
        default: false
      },
      isEdit: {
        type: Boolean,
        default: false
      },
      placement: {
        type: String,
        default: 'right'
      },
      tip: {
        type: String,
        default: ''
      },
      coverAttr: {
        type: String,
        default: ''
      },
      name: {
        type: String,
        default: ''
      },
      btnName: {
        type: String,
        default: '上传'
      },
      url: {
        type: String,
        default: ''
      },
      attr: {
        type: String,
        default: ''
      },
      formObj: {
        type: Object,
        default: ()=>{
          return {}
        }
      },
      defaultStyle: {
        type: Object,
        default: ()=>{
          return {}
        }
      }
    },
    data() {
      return {
        accept: 'image/png, image/jpeg, image/gif, image/jpg, image/webp',
        dialogVisibleImg: false,
        dialogType: ''
      }
    },
    created(){
      if(this.fileType=='all'){
        this.accept = 'video/*, image/png, image/jpeg, image/gif, image/jpg, image/webp'
      }else if(this.fileType=='video'){
        this.accept = 'video/*'
      }else{
        this.accept =  'image/png, image/jpeg, image/gif, image/jpg, image/webp'
      }
    },
    computed: {
     
    },
    methods: {
      isImage : util.isImage,
      handleLook(type) {
        this.dialogType = type
        this.dialogVisibleImg = true
      },
      addFile(){
        if(this.disabled) return;
        if(this.empty){
          this.$emit('clickEvent')
          return;
        }
        this.$refs.fileRef.click()
      },

      handleFileChange(e) {
        var file = e.srcElement.files[0]
        if(this.fileType=='video' && file.type?.indexOf('video')==-1) {
          this.$refs.fileRef.value = ''
          return this.$message.error('请上传mp4格式的视频')
        }
        if(this.fileType=='image' && file.type?.indexOf('image')==-1) {
          this.$refs.fileRef.value = ''
          return this.$message.error('请上传格式为jpg、jpeg、png、webp、gif的图片')
        }
        if(file.type?.indexOf('image')>-1){
          this.uploadImgFn(e)
        }else{
          this.uploadVideo(e)
        }
      },
      uploadImgFn(e) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        var file = e.srcElement.files[0]
        var reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = event => {
          const imgFile = event.target.result
          const arrBase64 = imgFile.split(',')
          const base64 = file.name.split('.').pop() + '@' + arrBase64[1]
          this.$apis.discover.uploadImgApi({file: base64,  fileType: 'image', compress: 1}).then(res => {
            this.formObj[this.attr] = res
            this.$emit('uploadSuccess', {attr : this.attr, url: res})
            this.$refs.fileRef.value = ''
            loading.close()
          }).catch(err => {
            this.$refs.fileRef.value = ''
            loading.close()
          })
        }
      },
      uploadVideo(e) {
        const self = this
        let file = e.target.files[0]
        const isLt = file.size / 1024 / 1024 < this.limitSize
        // if (!isLt) {
        //   this.$message.error('上传视频大小不能超过' + this.limitSize + 'MB!')
        //   return true
        // }
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        upload.init().then(res => {
          if (res.status == 0) {
            upload
              .uploaded(file)
              .then(res => {
                let url = res.video.url
                if(url && url.indexOf('https')<0){
                  url = url.replace('http','https')
                }
                self.formObj[self.attr] = url
                if(this.coverAttr) {
                  self.$nextTick(()=>[
                    self.getImgUrl(url).then(resp => {
                      self.$set(self.formObj, self.coverAttr, resp)
                      loading.close()
                    }).catch(err=>{
                      loading.close()
                    })
                  ])
                }else{
                  loading.close()
                }
                self.$refs.fileRef && (self.$refs.fileRef.value = '')
                self.$emit('uploadSuccess', {attr : self.attr, url})
              }).catch(end => {
                loading.close()
                self.$refs.fileRef && (self.$refs.fileRef.value = '')
              })
              upload.uploadEvent('', res => {
                console.log(res, '视频上传完成')
              })
              upload.uploadEvent('media_progress', res => {
                console.log(res)
              })
          }
        })
      },
      del(){
        this.formObj[this.attr] = ''
        this.$emit('delImage', {attr : this.attr})
      },
      edit() {
        this.$emit('editImage', {attr : this.attr})
      }
    }
  }
  </script>
  <style lang="scss" scoped>
  .upload-ctnr{
    display: flex;
    align-items: flex-end;
    .label{
      display: inline-block;
      vertical-align: top;
      width: 154px;
      height: 20px;
      font-size: 14px;
      color: #333333;
      text-align: right;
      line-height: 20px;
      box-sizing: border-box;
    }
    .tip {
      display: inline-block;
      font-size: 14px;
      color: #999999;
      height: 20px;
      line-height: 20px;
      margin-left: 8px;
      vertical-align: bottom;
    }
    .tip-bottom{
      display: block;
      margin-top: 8px;
      margin-left: 0;
    }
    .img-wrap{
      display: flex;

    }
    .img-item{
      display: inline-flex;
      border: 1px dashed #00000026;
      box-sizing: border-box;
      width: 104px;
      height: 104px;
      background: #0000000a;
      border-radius: 4px;
      position: relative;
      &:hover{
        .operate{
          display: block;
        }
      }
      .image{
        width: 100%;
        height: 100%;
        z-index: 2;
        position: relative;
      }

      .video-panel {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        video {
          position: absolute;
          object-fit: fill;
        }
        .el-icon-video-play {
          z-index: 10;
          font-size: 20px;
          color: #fff;
          cursor: pointer;
        }
        .el-icon-close {
          position: absolute;
          top: 0px;
          right: 0px;
          background: #000000;
          color: #fff;
        }
      }
      .add-img{
        width: 100%;
        height: 100%;
        cursor: pointer;
        display: inline-flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #666666;
        position: relative;
        .file{
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: -1;
          position: absolute;
          opacity: 0;
        }
        .add {
          font-size: 18px;
          font-weight: 500;
        }
        p {
          margin-top: 12px;
          height: 22px;
          line-height: 22px;
        }
      }
      .disabled{
        cursor: not-allowed;
      }
      .operate{
        display: none;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.4);
        border-radius: 4px;
        z-index: 5;
        .btn-wrap{
          color: #fff;
          white-space: nowrap;
          position: absolute;
          transform: translate(-50%, -50%);
          top: 50%;
          left: 50%;
          i{
            font-size: 16px;
            cursor: pointer;
            &:first-child{
              margin-right: 12px;
            }
          }
        }
      }
    }
  }
  </style>