vue上传附件

一、使用了vue的element ui上传组件

<el-form-item label="增加附件" prop="climb_cert" label-width="164px">
  <el-upload
    ref="upload"
    class="upload-demo"
    action="api/files_process/"
    :http-request="fileUpload"
    :file-list="fileList"
    :auto-upload="true"
    :show-file-list="true"
  >
    <el-button slot="trigger" size="small" type="primary" @click="setName('climb_cert')">点击上传</el-button>
  </el-upload>
</el-form-item>

二、在data中定义

export default {
  data() {
    return {
      fileName: '',
      fileList:[],
      calculatType: 'type',
    }
}

三、vue的methods中

setName(name) {
      this.fileName = name
    },
    fileUpload(param) {
      const loading = this.$loading({
        lock: true,
        text: '文件上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const fd = new FormData()
      fd.append('file', param.file)// 传文件
      fd.append('type', this.calculatType)// 传文件
      axios({
        method: 'post',
        url: '/api/files_process/',
        headers: {
          'Authorization': this.token,
          'content-type': 'multipart/form-data; boundary=<calculated when request is sent>'
        },
        data: fd
      }).then(res => {
        this.calculatForm[this.fileName] = res.data.data.file
        if (res.data.code === 20000) {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          loading.close()
        }
      })
    },
原文地址:https://www.cnblogs.com/paixiaoxin/p/14022911.html