element-ui upload 使用formData和不使用formData

前提:因为需求允许上传文件或不上传文件,尝试了用element-ui的upload写上传,探究怎样写最简洁

一、使用formdata


    
    
    
    

确 定

重点::http-request="submitUpload"

methods如下

    submitUpload(content) {
      const formData = new FormData()
      formData.append('file', content.file)
      formData.append('id', this.config.id)
      formData.append('kdmc', this.config.kdmc)
      formData.append('kddz', this.config.kddz)
      formData.append('jd', this.config.jd)
      formData.append('wd', this.config.wd)
      updateSysBase(formData)
        .then(resp => {
          this.showSuccessInfo(resp.msg)
          this.newImageName = ''
          this.$store.dispatch('GetConfig')
        })
        .finally(() => {
          this.sureDisabled = false
        })
    },
    submitAddForm() {
      this.$refs.config.validate(async result => {
        if (result) {
          if (this.newImageName) {
            await this.$refs.upload.submit()
          } else {
            this.config.logoImage = ''
            updateSysBase(this.config)
              .then(resp => {
                this.showSuccessInfo(resp.msg)
                this.newImageName = ''
                this.$store.dispatch('GetConfig')
              })
              .finally(() => {
                this.sureDisabled = false
              })
          }
        }
      })
    }

axios请求

export function updateSysBase(data) {
  return request({
    url: '/sysBase/updateSysBase',
    method: 'post',
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

request.js 也要相应改下trackId的携带方式,因为后台是在url所带参数那里判断的

if (config.data instanceof FormData) {
    // config.data.append('trackId', getToken())
    config.params = {
        trackId: getToken()
    }
}

二、不使用formData,发现其实不用formData写的代码更少一点


    
    
    

确 定

重点::with-credentials="true"  :data="config"

methods如下

    submitAddForm() {
      this.$refs.config.validate(async result => {
        if (result) {
          this.sureDisabled = true
          if (this.newImageName) {
            await this.$refs.upload.submit()
          } else {
            this.config.logoImage = ''
            updateSysBase(this.config)
              .then(resp => {
                this.showSuccessInfo(resp.msg)
                this.newImageName = ''
                this.$store.dispatch('GetConfig')
              })
              .finally(() => {
                this.sureDisabled = false
              })
          }
        }
      })
    }

 

你可能感兴趣的:(element-ui upload 使用formData和不使用formData)