Vue-上传文件

455 阅读1分钟

前言

文件上传是企业开发经常遇到的一个需求,在Element组件库也有现成的Upload组件可以很方便的直接调用。

代码

         <el-upload
            ref="upload"
            :limit="1"
            :before-upload="beforeUpload"
            :headers="headers"
            :on-success="handleSuccess"
            :on-error="handleError"
            action="https://tst-vwmep.faw-vw.com/api/oem/OemUserRegistrate/import"
          >
            <el-button type="primary" style="width: 160px">
              上传文件<i class="el-icon-upload el-icon--right"
            /></el-button>
          </el-upload>
          
    <script>
          export default {
  name: 'upload',
  data() {
    return {
      loading: false
      filename: ''
    }
  },
  methods: {
  
    // 上传文件
    async upload() {
      this.$refs.upload.submit()
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件格式有误,请按模板内容填写!')
      }
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      this.tableData = response ? response.data : []
      this.$refs.upload.clearFiles()
      this.$message.success('上传成功')
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$message.error(msg.message)
      this.loading = false
    },
   
  }
}
</script>