美文网首页
element-ui上传组件,before-upload里面如何

element-ui上传组件,before-upload里面如何

作者: 黎明的叶子 | 来源:发表于2021-10-19 11:01 被阅读0次

官方介绍:

before-upload:上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。
例子:

 methods: { 
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }

官方给的例子,里面判断了文件类型和大小。返回的是Boolean类型的true和false。

我的问题

那么介绍里面有写“返回Promise 且被 reject,则停止上传”。其实应该很容易想到,如果存在异步,就应该返回Promise。但是我看到的时候,没有理解透。还在想什么时候用Promise。恰巧我用到了异步,哪怕文件内容没有异步,只在方法前面加个async,如果仍然返回Boolean类型,就执行结果不对。
原因应该是async的原理就是返回promise了,如果结果是true和false,转换成promise后,promise的状态为fulfilled,结果为false,而已。那么仍然得到的是Promise.resolve方法一样。所以这时候即便为false。仍然可以执行上传操作。
于是我看了看源码,本来支持里面有异步的。所以我才意识到自己的问题。把处理后的结果直接用Promise.reject或者Promise.resolve就可以了。
源码如下:

// 源码中的方法 上传调用的
 upload: function upload(rawFile) {
      var _this2 = this;

      this.$refs.input.value = null;
      // 判断了是否有beforeUpload方法。没有直接上传了
      if (!this.beforeUpload) {
        return this.post(rawFile);
      }
      
     // 有的话 执行这个方法
      var before = this.beforeUpload(rawFile);
      // 这里判断执行结果。如果是Promise的,获取Promise的then方法。执行then方法,在then方法中继续判断
      if (before && before.then) {
        before.then(function (processedFile) {
          // 获取类型
          var fileType = Object.prototype.toString.call(processedFile);
        
          if (fileType === '[object File]' || fileType === '[object Blob]') {
            if (fileType === '[object Blob]') {
              processedFile = new File([processedFile], rawFile.name, {
                type: rawFile.type
              });
            }
            for (var p in rawFile) {
              if (rawFile.hasOwnProperty(p)) {
                processedFile[p] = rawFile[p];
              }
            }
            _this2.post(processedFile);
          } else {
            _this2.post(rawFile);
          }
        }, function () {
          // 返回的是Promise.reject的话 就执行执行的方法
          _this2.onRemove(null, rawFile);
        });
      } else if (before !== false) { // 如果before就是Boolean 则进入这里  不是false 直接提交了
        this.post(rawFile);
      } else {   // 这里不提交
        this.onRemove(null, rawFile);
      }
    },

相关文章

网友评论

      本文标题:element-ui上传组件,before-upload里面如何

      本文链接:https://www.haomeiwen.com/subject/auqtaltx.html