ant degign of vue文件上传

    <a-form-item
          v-show="false"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            v-decorator="['qrcodeUrl', {rules: [{required: false, message: '请上传二维码'}]}]">
          </a-input>
        </a-form-item>
        <a-form-item
          label="二维码"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-spin tip='Loading' :spinning="false">
          <a-upload
            name="file"  
            list-type="picture-card"
            :showUploadList="showUploadList" //是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon 和 showRemoveIcon
            :action="url"//后端文件上传接口
            :headers="headers"//请求头!
            :remove="handleFileRemove"//点击移除文件时的回调
            :beforeUpload="beforeFileUpload"//上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。支持返回一个 Promise 对象,Promise 对象 reject 时则停止上传,resolve 时开始上传( resolve 传入 File 或 Blob 对象则上传 resolve 传入对象)
        :fileList="defaultFileList"//已经上传的文件列表
        :customRequest="uploadFunc" //通过覆盖默认的上传行为,可以自定义自己的上传实现
    >
     <a-button :disabled='defaultFileList.length>0' v-if='!defaultFileList.length>0'> <a-icon type="upload"/> 上传二维码 </a-button> </a-upload>
    </a-spin>
</a-form-item>


data () {
    return {
      showUploadList: {
        showPreviewIcon: false,
        showRemoveIcon: true
      },
      url: process.env.VUE_APP_API_BASE_URL + '/storage/upload',
      defaultFileList: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      headers: {
        Authorization: 'Bearer ' + this.$store.state.user.token
      },
    }
  },
  methods: {
    // 自定义上传方法
    uploadFunc (file) {
      this.spinning = true
      const fileName = file.file.name
      const formData = new FormData()
      formData.append('file',file.file)
      upload(formData).then(res =>{
        this.spinning = false
        const item = {
          uid: res.data.newFileName,
          name: res.data.original_file_name,
          status: 'done',
          url: res.data.qrcode_url,
        }
        this.defaultFileList.push(item)
        file.onSuccess(res.data,file)
        this.$message.success('上传成功')
      }).catch(err=>{
        this.$message.error('上传失败')
        this.spinning = false
        file.onError(res.data,file)
      })
    },
   
    handleFileRemove (file) {
      const name = file.name
      this.defaultFileList = this.defaultFileList.filter(item => {
        if (name !== item.name) return item
      })
    },
    beforeFileUpload (file) {
      return new Promise((resolve, reject) => {
        const isJPG = file.type === 'image/jpeg'
        if (!isJPG) {
          this.$message.error('您只能上传jpg文件')
          return reject(new Error('您只能上传jpg文件'))
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('文件大小不能大于2MB')
          return reject(new Error('文件大小不能大于2MB'))
        }
        this.$message.info('文件正在上传中...')
        return resolve(true)
      })
    },
}

 handleOk () { //提交表单
this.form.validateFields(async (err, values) => {
if(this.defaultFileList.length<1){
this.$message.error('请上传二维码')
return
}
values.qrcodeUrl = this.defaultFileList[0].url
values.originalFileName = this.defaultFileList[0].name
if (!err) {
this.confirmLoading = true
try {
if (this.type === 'add') {
await addObj(values)
} else if (this.type === 'edit') {
await putObj(values)
}
setTimeout(() => {
this.confirmLoading = false
this.defaultFileList.pop()
this.$message.success('操作成功')
this.ImgKey = Math.random()
this.$emit('ok')
this.handleCancel()
}, 1500)
} catch (e) {
this.confirmLoading = false
this.$message .error(e.msg)
}
}
})
}
 

 表单的两项 分别为a-input输入框,绑定二维码的url,a-upload文件上传组件,用于上传二维码。注意上传组件的上传列表的内建样式和上传组件中的a-button的显示。

上传列表绑定的属性headers必须携带token,固定写法:

headers: {
Authorization: 'Bearer ' + this.$store.state.user.token
},
fileList属性绑定的是已经上传的文件列表(受控),我们默认让他是一个空数组。
beforeUpload属性绑定我们文件上传之前执行的方法,我们用它来检验上传的文件是否合法,方法返回一个Promise对象
customRequest绑定我们自定义的上传方法,方法接受一个参数file,我们new一个FormData对象用于数据的传输,formData.append('file',file.file)追加文件到表单数据,然后调用后端文件上传接口,参数为我们new的
FormData对象,上传成功之后把后端返回来的数据组成一个对象,push进我们绑定的fileList进行展示。
remove属性绑定的方法接受一个参数file,file是一个对象,得到file.name,由于上传组件可能上传多个文件,在删除的时候我们用数组的过滤器,筛选出和file.name不相同名称的文件,以达到移除选定文件的效果

 其中在保存表单的时候,我们会调用handleOk方法,我们检验表单字段,将文件列表的url属性赋值给qrcodeUrl表单项,进行保存。

 

原文地址:https://www.cnblogs.com/fxzemmm/p/14695263.html