vue elementUI upload 一次性自动上传多文件多图片的解决方案,多文件单接口,自动上传

<script src="//unpkg.com/vue@2/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.15.14/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<el-upload
  class="upload-demo"
  :name="uploadId"
  :ref="`Uploader-${uploadId}`"
  action=""
  list-type="picture-card"
  :on-remove="handleRemove"
   accept="image/*"
   multiple
  :file-list="fileList"
  :on-change="handleChange"
  :http-request="httpRequest"
  :auto-upload="false"
 >
  <el-button slot="trigger" size="small" type="primary">选取文件
  </el-button>
</el-upload>
</div>
var Main = {
    data() {
      return {
        fileList: [],
        uploadId: Math.random().toString(36).substr(2).toLocaleUpperCase(),
        uploadFiles: [],
        fm: new FormData(),
      };
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
    // 选择文件时,往fileList里添加
    handleChange(file, fileList) {
     //获取添加文件进来的状态
     (file.status == 'ready') && this.uploadFiles.push(file.raw);
     //获取原始文件的个数
     this.fileTotal = document.getElementsByName(this.uploadId)[0].files.length;
     //如果原始文件和upload的个数相同的时候就说明已经添加完了,可以触发上传的方法了
     if (this.uploadFiles.length === this.fileTotal) {
         //获取上传文件的组件
         const Uploader = this.$refs[`Uploader-${this.uploadId}`];
         //触发上传文件列表的方法
         Uploader.submit();
     }
    },
    // 批量上传
    httpRequest(file) {
      this.fm.append('file', file.file);
      if (this.fm.getAll('file').length === this.fileTotal) {
          this.$axios.post('https://jsonplaceholder.typicode.com/posts/', this.fm).then(res => {
            this.$message.success('图片上传成功!')
          }).catch(res => {
            this.$message.success('图片上传失败!')
          })
      }
      this.fileList = [];
    }
  }
}
Vue.prototype.$axios = axios
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值