element upload文件上传第二次上传失败的解决方法

<template>
  <div>
    <!-- 解决思路:设置limit可以上传2个文件,但上传2个文件成功后,默认把第一个文件去掉,只保留最后上传的文件 -->
    <el-upload action="#" :auto-upload="true" :limit="2" :on-change="changeFiles" :before-upload="beforeUpload" :on-success="uploadSuccess" :on-error="uploadError" :on-remove="removeFilePath" :on-exceed="onExceed" ref="myUpload">
      <el-button size="small" slot="trigger">上传文件</el-button>
      <div slot="tip" class="el-upload__tip" v-if="showFileTips">
        {{
          "只支持上传" + getAcceptFileTips + "文件"
        }}
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'myUploadCompoent',
  data() {
    return {}
  },
  model: {
    prop: 'fileInfo',
    event: 'change'
  },
  props: {
    fileInfo: Object,
    customFileTips: { type: String, default: '' },
    showFileTips: { type: Boolean, default: true },
    disabled: {
      type: Boolean,
      default: false
    },
    //接收的文件类型
    acceptFileArr: {
      type: Array,
      default: function () {
        return ['.txt', '.doc']
      }
    },
  },
  computed: {
    getAcceptFileTips() {
      return this.acceptFileArr.join(' ')
    }
  },
  mounted() {},
  methods: {
    beforeUpload(res) {
      // 获取当前上传文件的类型
      if (this.acceptFileArr?.length > 0 && res?.name) {
        let nowFileType = ''
        try {
          nowFileType = res.name.substring(res.name.lastIndexOf('.'))
        } catch (error) {
          nowFileType = ''
        }
        if (nowFileType && this.acceptFileArr.indexOf(nowFileType) === -1) {
          //给出提示:请上传正确格式的文件
          return false
        }
      }
      return true
    },
    changeFiles(file, fileList) {
      //解决思路:设置limit可以上传2个文件,但上传2个文件成功后,默认把第一个文件去掉,只保留最后上传的文件
      if (fileList.length > 1) {
        fileList.shift()
      }
    },
    uploadError() {
      // 文件上传失败
    },
    uploadSuccess(res, file, fileList) {
      if (res?.data?.path) {
        this.fileInfo.path = res.data.path
        this.$emit('fileChange', this.fileInfo)
      }
    },
    onExceed(res, file) {},
  }
}
</script>

<style lang="less" scoped></style>

你可能感兴趣的:(elementui,vue.js,前端,javascript)