el-upload 多文件上传&按顺序上传

970 阅读1分钟

最近遇到一个需求:el-upload 多文件上传&按顺序上传

upload上传逻辑

<el-upload class="upload-demo" drag ref="uploadRef" multiple :onChange="onChange" accept="image/*" :auto-upload="false"
  :action="''" :limit="10" :show-file-list="false">
  <template v-if="form.imgVoList.length > 0">
    <div v-for="(item, index) in form.imgVoList" :key="index" class="template-img_item">
      <img :src="item.templateImgUrl + '?q_10'" alt="" />
      <div class="delete-img" @click.stop="handleRemoveFile(index)">删除</div>
    </div>
  </template>
  <template v-else>
    <div style="width: 100%">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
      <div class="el-upload__text">
        最多上传 <span style="color: red; font-weight: bold">10</span> 张
      </div>
    </div>
  </template>
</el-upload>

上传逻辑 方法

...
data(){
return {
  waitUploadList: [],
  uploadFlag: false,
}
},
methods:{
  onChange(file) {
      if (this.uploadFlag) {
        return this.waitUploadList.push(file.raw)
      }
      this.uploadFlag = true
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      const formData = new FormData()
      formData.append('file', file.raw)
      this.$upload('/system/oss/upload', formData)
        .then((res) => {
          const { code, data } = res
          if (code == 200) {
            this.form.imgVoList.push({
              templateImgUrl: data.url,
              combinationTemplateId: this.selectedTemplate,
            })
            this.uploadFlag = false
            this.uploadRestFile()
          }
        })
        .finally(() => loading.close())
    },
    /**上传翻个文件 */
    uploadSingleFile() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      const formData = new FormData()
      const file = this.waitUploadList.shift()
      formData.append('file', file)
      this.$upload('/system/oss/upload', formData)
        .then((res) => {
          const { code, data } = res
          if (code == 200) {
            this.form.imgVoList.push({
              templateImgUrl: data.url,
              combinationTemplateId: this.selectedTemplate,
            })
            this.uploadRestFile()
          }
        })
        .finally(() => loading.close())
    },

    /**上传剩余文件 */
    uploadRestFile() {
      if (this.waitUploadList.length > 0) {
        this.uploadSingleFile()
      }
    },
}

搞定 , 此处记录是为了以后可能会用到