ant design of vue 之图片上传组件(一张)(腾讯云)封装

安装cos-js-sdk-v5依赖

npm i cos-js-sdk-v5 --save

参考cos-js-sdk-v5

uuid.js文件

在src的utils文件夹中新增uuid.js文件

/* eslint-disable */
export default (len, radix) => {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

  var uuid = [],
    i;
  radix = radix || chars.length;
  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
  } else {
    // rfc4122, version 4 form
    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';
    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuid.join('');
}

system.config.js文件

在src的config文件夹中新增system.config.js文件

/**
 * 系统配置文件
 */
/* eslint-disable */
// 系统配置 ,在模块中使用方法: this.$CONFIG.xxxx 
const config = {
  //系统名称
  systemTitle:'安全生产标准化管理体系网',
  //系统描述
  systemDescription:'业界领先的信息聚合平台',
  //系统底部 copyright@公司名称
  footerComName:'信息科技有限公司',
  //腾讯云存储
  Bucket: 'test-1256342487',
  Region: 'ap-chengdu',
  //后台接口地址
  serverUrl:'http://123.206.76.136/news/api'
  
}
export default config

在main.js文件中进行全局属性配置

import config from '@/config/system.config'
// 引入全局自定义配置文件
Vue.CONFIG = Vue.prototype.$CONFIG = config

封装组件

<template>
  <a-upload
    class="avatar-uploader"
    listType="picture-card"
    :showUploadList="false"
    :beforeUpload="beforeUpload"
    @change="handleChange"
  >
    <div class="upload-list-item" v-if="imageUrl">
      <img style="width:120px;height:80px;" :src="imageUrl" alt="avatar" />
      <span class="upload-list-item-actions" @click.stop="remove">
        <a-icon theme="twoTone" twoToneColor="#f5222d" type="close-circle" />
      </span>
    </div>
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">
        {{ loading ? '上传中...' : '上传' }}
      </div>
    </div>
  </a-upload>
</template>
<script>
import COS from 'cos-js-sdk-v5'
import { getCredential } from '@/api/upload'
import uuid from '@/utils/uuid'
export default {
  name:"UploadImageOne",
  props: ['defaultImageUrl', 'uploadType'],
  data() {
    return {
      loading: false,
      imageUrl: '',
      cos: null
    }
  },
  watch: {
    defaultImageUrl(newVal) {
      this.imageUrl = newVal
    }
  },
  created() {
    this.imageUrl = this.defaultImageUrl
    this.cos = new COS({
      getAuthorization: (options, callback) => {
        getCredential().then(res => {
          if (res.success == true) {
          	const { result } = res
            callback({
              TmpSecretId: result.tmpSecretId,
              TmpSecretKey: result.tmpSecretKey,
              XCosSecurityToken: result.sessionToken,
              ExpiredTime: result.expiredTime
            })
            } else {
            this.$message.error(res.msg)
          }
        })
      }
    })
  },
  methods: {
  remove(index) {
    this.imageUrl = ''
    this.$emit('change', this.imageUrl)
  },
  handleChange(info) {
      const { file } = info
      this.imageUrl = ''
      this.loading = true
      const that = this
      const uid = uuid(32)
      const extName = that.getExtName(file.name)
      const fileName = file.name
      this.cos.sliceUploadFile(
        {
          Bucket: that.$CONFIG.Bucket,
          Region: that.$CONFIG.Region,
          Key: fileName,
          Body: file
        },
        (err, data) => {
          if (!err) {
            const { Location } = data
            this.imageUrl = 'http://' + Location
            this.$emit('change', this.imageUrl)
          }
          this.loading = false
        }
      )
    },
    beforeUpload(file) {
      if (this.uploadType == 'pic') {
        let isJPG = false
        const picTypes = ['image/jpeg', 'image/png', 'image/bmp', 'image/tif']
        for (let i = 0; i < picTypes.length; i++) {
          if (file.type.toLocaleLowerCase() == picTypes[i]) {
            isJPG = true
            break
          }
        }
        if (!isJPG) {
          this.$message.error('请上传图片类型:jpeg/png/bmp/tif!')
          return true
        }
      }
      return false
    },
    /**
     * 获取后缀名
     */
    getExtName(fileName) {
      let index = fileName.lastIndexOf('.')
      if (index > -1) {
        return fileName.substring(index + 1)
      } else {
        return ''
      }
    }
  }
}
</script>
<style lang="less">
.ant-upload-select-picture-card i {
  font-size: 20px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.upload-list-item {
  position: relative;
}
.upload-list-item-actions {
  position: absolute;
  right: 0;
  top: 0px;
  padding: 0 10px;
  // -webkit-transform: translate(-50%, -50%);
  // transform: translate(-50%, -50%);
  z-index: 10;
  white-space: nowrap;
  opacity: 0;
  transition: all 0.3s;
  cursor: pointer;
}
.upload-list-item:hover {
  .upload-list-item-actions {
    opacity: 1;
  }
}
</style>

使用

import UploadImageOne from '@/components/UploadImageOne'
<upload-image-one ref="UploadImageOne" 
					@change="onSkuUploadChange" 
					:defaultImageUrl="content" 
					:uploadType="uploadType"></upload-image-one>
uploadType: 'pic',
onSkuUploadChange (imageUrl) {
  console.log(imageUrl)
},
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值