fujianList copy 2.vue 7.86 KB
<template>
  <el-upload
    :auto-upload="false" multiple :action="uploadFileUrl" :accept="fileType" :on-change="handleUpload":on-success="handleUploadSuccess"
     :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed" :on-remove="handleRemove" :headers="headers" :file-list="fileList"
      :on-preview="handlePictureCardPreview" :class="{hide: this.fileList.length >= this.limit}">
    <div style="display: flex;align-items: center;">
      <el-button v-if="fileList.length < limit" style="background-color: #fff;color: #000;border: 1px solid #dcdfe6;" class="buttonHover">
        <div style="display: flex;align-items: center;">
          <img src="@/assets/images/upload.png" style="width: 16px;height: 16px;margin-right: 4px;" alt="">
          <span style="">上传附件</span>
        </div>
      </el-button>
      <div v-if="fileList.length < limit" slot="tip" class="tips" style="margin-left: 10px;">不超过{{ fileSize }}MB</div>
    </div>
  </el-upload>
</template>
<script>
  import {
    miniioupload
  } from '@/api/commodityLease.js'
  // import { getAccessToken } from '@/utils/auth'
  import {
    uploadUrl
  } from '@/utils/request'
  export default {
    props: {
      value: [String, Object, Array],
      // 图片数量限制
      limit: {
        type: Number,
        default: 1
      },
      filePath: {
        type: String,
        default: 'other'
      },
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 5
      },
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
        type: String,
        default:'.bmp,.jpg,.jpeg,.png',
      },
      // 是否显示提示
      isShowTip: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        
        host: '',
        number: 0,
        uploadList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        hideUpload: false,
        uploadFileUrl: uploadUrl, // 请求地址
        headers: {
          Authorization: ''
        }, // 设置上传的请求头部
        fileList: [],
      }
    },
    computed: {
      // 是否显示提示
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize)
      }
    },
    watch: {
      value: {
        handler(val) {
          if (val) {
            // 首先将值转为数组
            this.uploadList = []
            const list = Array.isArray(val) ? val : this.value.split(',')
            // 然后将数组转为对象数组
            for (const item of list) {
              if (typeof item === 'string') {
                let info = {
                  name: this.$baseURL+item,
                  url: this.$baseURL+item
                }
                this.uploadList.push(item)
                this.fileList.push(info)
              }
            }
          } else {
            this.uploadList = []
            this.fileList = []
            return []
          }
        },
        deep: true,
        immediate: true
      }
    },
    methods: {
      checkFileType(file) {
        console.error(file)
        let {
          accept
        } = this.options;
        if (!accept || accept === '*') {
          return true;
        }
        accept = accept.toLowerCase().replace(/\s/g, '');
        const acceptTypeList = accept.split(',');
        const fileType = file.name.match(/\.\w*$/)?.shift() ?? '';
        return acceptTypeList.includes(fileType.toLowerCase());
      },
      checkSize({
        size
      }) {
        return size <= this.options.limitSize * 1024 * 1024;
      },
      filesCheck(files) {
        const limit = this.limit;
        const limitSize = this.fileSize;
        const accept = this.fileType;
        if (this.uploadList.length + files.length > limit) {
          this.$message.error(`最多上传${limit}个文件`);
          return false;
        }
        for (let index = 0; index < files.length; index++) {
          const file = files[index];
          if (!this.checkFileType(file)) {
            this.$message.error(`请上传${accept}等格式`);
            return false;
          }
          if (!this.checkSize(file)) {
            this.$message.error(`文件大小不能超过 ${limitSize}MB!`);
            return false;
          }
        }

        return true;
      },
      handleUpload(response) {
        // if (!this.filesCheck(response)) {
        //   return;
        // }
        // console.error(response)
        // return
        let fd = new FormData()
        fd.append('file', response.raw)
        fd.append('filePath',this.filePath)
        miniioupload(fd).then(res => {
          console.error(res)
          const fileMsg = {
            name: response.name,
            url: this.$baseURL + res.data,
          }
          this.fileList.push(fileMsg)
          this.uploadList.push(res.data)
          this.$emit('changimg',this.uploadList.join(','))
        })
      },
      // 删除图片
      handleRemove(file, fileList) {
        this.fileList = []
        this.uploadList = []
        this.$emit('changimg',this.uploadList.join(','))
        // const findex = this.fileList.map(f => f.name).indexOf(file.name)
        // if (findex > -1) {
        //   this.fileList.splice(findex, 1)
        //   this.uploadList.splice(findex, 1)
          
        // }
      },
      // 上传成功回调
      handleUploadSuccess(res) {
        this.uploadList.push({
          name: res.data.url,
          url: res.data.url
        })
        console.log(this.uploadList)
        if (this.uploadList.length === this.number) {
          this.fileList = this.fileList.concat(this.uploadList)
          this.uploadList = []
          this.number = 0
          this.$emit('input', this.listToString(this.fileList))
          // this.$modal.closeLoading()
        }
      },
      // 上传前loading加载
      handleBeforeUpload(file) {
        // let isImg = false
        // if (this.fileType.length) {
        //   let fileExtension = ''
        //   if (file.name.lastIndexOf('.') > -1) {
        //     fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        //   }
        //   isImg = this.fileType.some(type => {
        //     if (file.type.indexOf(type) > -1) return true
        //     if (fileExtension && fileExtension.indexOf(type) > -1) return true
        //     return false
        //   })
        // } else {
        //   isImg = file.type.indexOf('image') > -1
        // }

        // if (!isImg) {
        //   this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`)
        //   return false
        // }
        // if (this.fileSize) {
        //   const isLt = file.size / 1024 / 1024 < this.fileSize
        //   if (!isLt) {
        //     this.$message.error(`上传头像图片大小不能超过 ${this.fileSize} MB!`)
        //     return false
        //   }
        // }
        // this.$message.warning('正在上传图片,请稍候...')
        // this.number++
      },
      // 文件个数超出
      handleExceed() {
        this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`)
      },
      // 上传失败
      handleUploadError() {
        this.$message.error('上传图片失败,请重试')
        // this.$modal.closeLoading()
      },
      // 预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 对象转成指定字符串分隔
      listToString(list, separator) {
        let strs = ''
        separator = separator || ','
        for (const i in list) {
          strs += list[i].url.replace(this.baseUrl, '') + separator
        }
        return strs !== '' ? strs.substr(0, strs.length - 1) : ''
      }
    }
  }
</script>
<style lang="scss" scoped>
  ::v-deep .el-upload {
    text-align: left !important;
  }
  .tips {
      color: #0006;
      font: 14px 'Alibaba PuHuiTi 2.0-55 Regular';
      line-height: 38px;
    }
</style>