【antd Vue】封裝upload圖片上傳組件(返回Base64)

最近需要把上傳的圖片信息存儲到數(shù)據(jù)庫,以base64的方式,需要重新封裝一下antd的upload組件

1. 使用方法

引入組件然后配置一下即可使用,配置項(xiàng)包括

  • defaultImageList,需要回顯的圖片(必傳),[ url1, url2 ]
  • fileTypeList ,文件格式(可選),默認(rèn)不做限制
  • limitSize ,單個圖片大小限制(可選),單位MB
  • limitNum ,上傳圖片個數(shù)限制(可選),默認(rèn)200個
  • multiple ,是否可以多選(可選),默認(rèn)否
  • disabled ,是否禁用(可選),默認(rèn)否
  1. 引用組件
<template>
  <div>
    <b-upload-image-base64 ref="bUploadImageBase64" :limitNum="1" @change="change" :defaultImageList="data" />
  </div>
</template>
<script>
  import bUploadImageBase64 from '@/components/BUploadImageBase64'
  export default {
    components: {
      bUploadImageBase64
    },
    data() {
      return {
        data: ['https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'],
        defaultImageList: []
      };
    },
    methods: {
      change(e) {
        console.log('e', e)
      }
    },
  };
</script>
<style>

</style>
  1. 組件
<template>
  <div class="clearfix">
    <a-upload
      :beforeUpload="beforeImageUpload"
      list-type="picture-card"
      :file-list="imageList"
      :multiple="multiple"
      :disabled="disabled"
      @change="handleImageChange"
      @preview="handlePreview"
      :custom-request="customRequest"
    >
      <div v-if="imageList.length < limitNum && !disabled">
        <a-icon type="plus"/>
        <div class="ant-upload-text">上傳</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>
<script>
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }

  export default {
    props: {
      defaultImageList: {
        type: Array,
        default: function() {
          return []
        },
        required: true
      },
      fileTypeList: {
        type: Array,
        default: function() {
          return []
        },
        required: false
      },
      limitSize: {
        type: Number,
        default: 5,
        required: false
      },
      limitNum: {
        type: Number,
        default: 20,
        required: false
      },
      multiple: {
        type: Boolean,
        default: false,
        required: false
      },
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data() {
      return {
        previewVisible: false,
        previewImage: '',
        imageList: []
      }
    },
    watch: {
      defaultImageList(newVal) {
        this.imageList = this.handleData(newVal)
      }
    },
    created() {
      this.imageList = this.handleData(this.defaultImageList)
    },
    methods: {
      // ---------------------------------------------img--start
      beforeImageUpload(file) {
        return new Promise((resolve, reject) => {
          if (!this.fileTypeList) {
            const index = this.fileTypeList.indexOf(file.type)
            if (index > 0) {
              this.$message.error(`您只能上傳${this.fileTypeList[index]}文件`)
            }
          }
          const limitSize = file.size / 1024 / 1024 < this.limitSize
          if (!limitSize) {
            this.$message.error(`文件大小不能大于${this.limitSize}MB`)
            return reject(new Error(`文件大小不能大于${this.limitSize}MB`))
          }
          return resolve(true)
        })
      },
      async handlePreview(file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      handleCancel() {
        this.previewVisible = false
      },
      customRequest({ action, file, onSuccess, onError, onProgress }) {
        new Promise(resolve => {
          const fileReader = new FileReader()
          fileReader.readAsDataURL(file)
          fileReader.onload = () => {
            let index = {
              uid: this.genId(5),
              name: file.name,
              status: 'done',
              url: fileReader.result
            }
            this.imageList = [...this.imageList.filter(item => item.status === 'done'), index]
            this.$message.success('文件上傳成功!')
            this.handleChange()
            resolve(fileReader.result)
          }
        })
      },
      handleImageChange(info) {
        let fileList = [...info.fileList]
        this.imageList = fileList
        this.handleChange()
      },
      handleChange() {
        let index = this.imageList.filter(item => item.url).map(item => {
          return item.url
        })
        this.$emit('change', index ? index : [])
      },
      genId(length) {
        return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36)
      },
      handleData (list) {
        return list.map(item => {
          let index = this.genId(5)
          return {
            uid: index,
            name: index,
            status: 'done',
            url: item
          }
        })
      }
      // ---------------------------------------------img--end
    }
  }
</script>
<style>
  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>

2. 封裝遇到的坑

因?yàn)槭亲约簩?shí)現(xiàn)上傳邏輯需要使用屬性:custom-request="customRequest"
組件的運(yùn)行順序是beforeImageUpload->customRequest

  1. 一開始的校驗(yàn)需要寫在beforeImageUpload中,主要是驗(yàn)證文件格式,文件大小
  2. 然后進(jìn)入自定義的上傳邏輯,這里主要是讀取圖片為base64,然后放入回顯的數(shù)組中,這樣組件就可以顯示上傳的圖片了,此時還需要回調(diào)base64
  3. handleChange方法主要是刪除圖片使用,需要過濾出非undefined的,剩余的圖片并回傳base64
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容