<template>
    <div>
      <a v-if="isShowChromeTip">
              &nbsp;<input ref="file" type='file' name="file" webkitdirectory @change.stop="changesData"/>
      </a>
      <div class="ui primary button" @click="uploadQRCode()" style="margin-left: 10px">
              上传
      </div>
    </div>
</template>
<script>
 export default {
    name: 'catchRes',
    data: function () {
        return {
        }
    }
    computed: {
           //判断是否为chrome浏览器,chrome支持上传文件夹
      isShowChromeTip() {
        const USER_AGENT = navigator.userAgent.toLowerCase();
        const isChrome = /.*(chrome)\/([\w.]+).*/;
        return isChrome.test(USER_AGENT);
      }
    },
    methods:{
        changesData() {
        let files = this.$refs.file.files;
        let that = this;
        for (let i of files) {
          let reader = new FileReader();//创建读取文件的方法
          let item = {};
            //筛选出文件夹下的图片
          if (i.type === "image/png") {
            //获取图片前一个文件夹名
            let index1 = i.webkitRelativePath.indexOf('/' + i.name);
            let path1 = i.webkitRelativePath.slice(0, index1);
            let index2 = path1.lastIndexOf('/');
            let path2 = path1.slice(index2 + 1);
            let blob = null;
            item.website = path2
            //转化为binary类型
            reader.readAsArrayBuffer(i)
            reader.onload = (e) => {
              if(typeof e.target.result === 'object'){
                blob = new Blob([e.target.result])
              }else{
                blob = e.target.result
              }
              item.qrcode = blob;
              that.QRCodeList.push(item)
            }
          }
        }
      },
      uploadQRCode() {
        let that = this;
        this.sendRequest(that.QRCodeList, 10, function () {
          console.log('上传完成');
        })
      },
        //将参数传到后台
      sendRequest(params, max, callback) {
        let finished = 0; //当前并发量
        const total = params.length;
        const handler = () => {
          if (params.length) {
            const param = params.shift();
            console.log(params)
            let formData = new FormData();
            formData.append('website', param.website);
            formData.append('qrcode', param.qrcode);
            console.log(param.website, param.qrcode)
            fetch("url", {method: 'POST', body: formData})
              .then(res => res.json())
              .then(res => {
                  finished++;
                  handler();
                  console.log(res.retcode === 0 ? "上传图片成功" : ("上传图片失败:" + res.retmsg));
                }
              ).catch(e => {
                throw Error(e);
            })
          }
          if (finished >= total) {
            callback();
          }
        }
        for (let i = 0; i < max; i++) {
          handler();
        }
      },
    }
    
}
</script>

Logo

前往低代码交流专区

更多推荐