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

封装组件

/* eslint-disable space-before-function-paren */ 
/* eslint-disable space-before-function-paren */ 
//eslint-disable-next-line vue/valid-template-root
<template>
  <div class="clearfix">
    <a-upload name="file"
              :multiple="true"
              :showUploadList="true"
              :remove="remove"
              :fileList="fileList"
              :beforeUpload="beforeUpload"
              :customRequest="customRequest"
              :accept="accept.join(',')"
              class="upload-list-inline"
              listType="picture">
      <a-button v-if="fileList.length < maxLength">
        <a-icon type="upload" />上传
      </a-button>
    </a-upload>
  </div>
</template>
import COS from 'cos-js-sdk-v5'
import { getCredential } from '@/api/upload'
import uuid from '@/utils/uuid'
export default {
  name: 'UploadFile',
  props: {
    /**
   * 格式示例:
   * [{
        uid: '-1',
        name: 'xxx.png',
        status: 'done',
        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      }]
             */
    files: {
      type: Array,
      required: false,
      default: () => []
    },
    maxLength: {
      type: Number,
      required: false,
      default: () => 1000
    },
    maxSize: {
      type: Number,
      required: false,
      default: () => 102400
    },
    editable: {
      type: Boolean,
      required: false,
      default: () => true
    },
    accept: {
      type: Array,
      required: false,
      default: () => []
    }
  },
  data () {
    return {
      cos: null,
      fileList: []
    }
  },
  watch: {
    files (list) {
      this.fileList = list
    }
  },
  created () {
    // 初始化腾讯云上传
    this.cos = new COS({
      getAuthorization: (options, callback) => {
        getCredential().then(data => {
          callback({
            TmpSecretId: data.tmpSecretId,
            TmpSecretKey: data.tmpSecretKey,
            XCosSecurityToken: data.sessionToken,
            ExpiredTime: data.expiredTime
          })
        })
      }
    })
  },
  methods: {
    // 上传之前判断文件大小   即使选择多个文件,beforeUpload也会调用多次
    beforeUpload (file) {
      // 文件小于100M才能上传
      const isSize = Number((file.size / 1024).toFixed(2)) > this.maxSize
      if (isSize) {
        this.$message.error('请上传文件小于100M')
        return false
      } else {
        return true
      }
    },
    customRequest (info) {
      const { file } = info
      // debugger
      const that = this
      const uid = uuid(32)
      const extName = that.getExtName(file.name)
      // const fileName = `${uid}.${extName}`
      const fileName = that.getFileName(file.name) + '' + (new Date()).getTime() + '.' + extName
      const size = Number((file.size / 1024).toFixed(2))
      const { accept } = that
      if (accept.length && !accept.includes(`.${extName}`.toLowerCase())) {
        that.$message.error('文件格式错误')
        return
      }
      this.cos.putObject(
        {
          Bucket: that.$CONFIG.Bucket,
          Region: that.$CONFIG.Region,
          Key: fileName,
          Body: file, // 上传文件对象
          onProgress: progressData => {
            // that.progress = progressData.percent
          }
        },
        function (err, data) {
          if (err) {
            that.$notification.error({
              message: '文件上传错误',
              description: err.Message
            })
          } else {
            const url = `http://${data['Location']}`
            that.fileList.push({
              uid,
              size,
              name: file.name,
              type: file.type,
              status: 'done',
              url,
              rename: fileName,
              extName,
              thumbnailUrl: url
            })
            that.$emit('change', that.fileList)
          }
        }
      )
    },
    remove (file) {
      const that = this
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      that.$emit('change', that.fileList)
    },
    getExtName (fileName) {
      const index = fileName.lastIndexOf('.')
      if (index > -1) {
        return fileName.substring(index + 1)
      } else {
        return ''
      }
    },
    getFileName (fileName) {
      const index = fileName.lastIndexOf('.')
      if (index > -1) {
        return fileName.slice(0, index)
      } else {
        return ''
      }
    }
  }
}
</script>
<style scoped>
/* tile uploaded pictures */
.upload-list-inline >>> .ant-upload-list-item {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline >>> .ant-upload-animate-enter {
  animation-name: uploadAnimateInlineIn;
}
.upload-list-inline >>> .ant-upload-animate-leave {
  animation-name: uploadAnimateInlineOut;
}
</style>

使用

<upload-file 
	:accept="['.doc','.docx','.ppt','.pptx','.pdf','.pdfx','.xls','.xlsx']"
	:files="fileList" 
	@change="uploadFile"></upload-file>
// 上传附件返回数据
    uploadFile(files){
     console.log("uploadFile",files)
     this.articleAttachmentList = files.map(item=>({
       attachmentExtensionName:item.extName,//文件扩展名
       attachmentLogicalFilename:item.name,//文件显示名
       attachmentPhysicalFilename:item.rename,//文件存储名
       attachmentSize:item.size,//文件大小
       attachmentUrl:item.url,//文件路径
     }))
   },

// 获取数据给组件显示
this.fileList = articleAttachmentList.map((item,index)=>({
   uid:index,
   name: item.attachmentLogicalFilename,
   status:"done",
   url: item.attachmentUrl,
   reName: item.attachmentPhysicalFilename,
   extName: item.attachmentExtensionName,
   size:0,
   thumbnailUrl:""
 }))
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: Ant Design of Vue 是一个基于 Vue.js 的 UI 组件库,它提供了丰富的组件和样式,可以帮助开发者快速构建美观、易用的 Web 应用程序。其中,Ant Design of Vue 表单封装是一个非常实用的功能,它可以帮助开发者快速构建表单,包括表单验证、表单布局、表单提交等功能,大大提高了开发效率。同时,Ant Design of Vue 表单封装还支持自定义表单组件,开发者可以根据自己的需求定制表单组件,满足不同的业务需求。总之,Ant Design of Vue 表单封装是一个非常实用的功能,可以帮助开发者快速构建高质量的 Web 应用程序。 ### 回答2: Ant Design of Vue是一个基于Vue.js的UI组件库,它提供了一系列优雅且易用的组件,包含有丰富的UI组件、样式和交互行为,可以帮助我们快速构建漂亮而且功能强大的Web应用。 其中,表单是Ant Design of Vue中最核心、最常用的组件之一,因为表单是我们在前端开发中最常用的交互方式。Ant Design of Vue中针对表单封装的功能也非常丰富,主要包括以下几个方面: 1. 表单控件:Ant Design of Vue提供了一系列的表单控件,包括输入框、选择器、日期选择器、开关、单选框、复选框等,这些表单控件都有丰富的属性和事件可以自由控制,可以满足我们在不同的场景下的需求。 2. 表单校验:Ant Design of Vue提供了非常强大的表单校验功能,可以对表单进行必填、数据格式、长度等多个方面的校验,还可以自定义校验规则,方便我们在项目中灵活运用。 3. 表单布局:Ant Design of Vue提供了多种表单布局,包括水平布局、垂直布局、行内布局等,可以根据不同的需求选择不同的布局方式,在表单的美观性、可读性等方面都有很好的表现。 4. 表单数据处理:Ant Design of Vue提供了非常便捷的表单数据处理方式,可以将表单中的数据进行组装、序列化、反序列化等操作,快捷方便。 总之,Ant Design of Vue提供的表单封装功能非常丰富、易用,在我们的前端开发中应用广泛,可以大大提高我们的开发效率、代码质量和用户体验。 ### 回答3: Ant Design of Vue 是一个企业级 UI 设计语言和 Vue.js 的实现版本,其中包括了许多常用的组件,如表格、表单、对话框等。 在 Ant Design of Vue 中,表单是一个非常常用和重要的组件,用于网站的交互和数据处理。Ant Design of Vue 中的表单组件可以通过简单的代码来实现各种表单元素的布局、样式、校验和提交等功能,同时具有良好的用户体验和可维护性。 Ant Design of Vue 的表单封装主要包括三个部分:表单组件、表单项组件和校验规则。 表单组件Ant Design of Vue 中的一个顶层组件,用于包装整个表单。通过定义 props 来配置表单的属性和事件,例如表单的布局方式、表单项组件的数据和样式绑定、表单的提交和重置等。 表单项组件是表单中的一个子组件,用于表示一个表单的输入项,如输入框、单选框、复选框和下拉框等。通过定义 props 和 v-model 来绑定表单项和表单数据,并设置相应的属性和事件来实现校验、关联、联动和交互等功能。 校验规则是 Ant Design of Vue 中用于校验表单项数据合法性的组件。通过定义 rules 属性来配置校验规则,例如数据格式、数据类型、数据范围和数据比较等。当表单提交或失焦时,校验规则会自动进行校验,并在校验不通过时提示相应的错误信息。 总体来说,Ant Design of Vue 中的表单封装具有很高的可用性和可扩展性,能够满足各种不同的业务需求,并且对于前端开发人员来说也十分友好和方便。如果您需要构建一个高品质的企业级表单,那么 Ant Design of Vue 的表单封装一定是您的不二之选。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值