undefinedfix
Sign in

The problem of return value supported by before upload of antd upload component

KTH edited in Sat, 28 Nov 2020

Now I need to write a method to return true or false by judging the length of the image and the size of the file

console.log('file want upload ', file);
    let reader = new FileReader();
    reader.readAsDataURL(file);
    if (file.size > 1024*1024*3) { // 大于3M
      message.error('您上传的图片过大!请重新上传');
      return false;
    }
    let img = new Image();
    return (function () {
      let flag: boolean=true;
      ((flag) => {
        reader.onloadend = function(evt){
          img.src    = this.result;
          let width  = img.width;
          let height = img.height;
          console.log(width);
          console.log(height);
          if (width < 2000 && height < 2000) {
            flag = true;
          } else {
            flag = false
          }
        }
      })(flag)
      return flag;
    })()

But it is obvious that the function will return first. So modifying the flag value in onloadend is actually invalid. What should I do to make the outer function return the result after onloadend?

========Update = = = = = = it is precisely because the beforeupload of the upload component is judged to be false when return promise.. therefore, this effect cannot be realized.. can it be improved?

4 Replies
luprchal
commented on Sat, 28 Nov 2020

Before upload can return a promise Code:

:before-upload="beforePosterUpload"

methods:{
    ...
    beforePosterUpload(file){ // 绑定在
      this.uplaodData.key = '';
      return this.beforeUploadImg(file,true); //带尺寸
    },
    beforeUploadImg(file,hasSize){
      let _URL = window.URL || window.webkitURL;    
      let img = new Image();
      img.src = _URL.createObjectURL(file); 
      let size = '';
      let key = '';
      let that = this;
      // 返回promise
      return new Promise(function(resolve,reject){
        img.onload = ()=>{
          size = 'wd_'+ img.width +'×'+ img.height;
          key = new Date().getTime()+'_'+that.rndNum(5); //七牛上存储的名字
          that.uplaodData.key = key+(hasSize?size:'');
          that.getToken();
          resolve(); // 处理完成后resolve();
        }
      });
    },
    ...
}
cuteday
commented on Sun, 29 Nov 2020

setTimeOut?

Conrado
commented on Sun, 29 Nov 2020

Introduce asynchronous process control.. Promise or something

suxbr
commented on Sun, 29 Nov 2020

It should be impossible.

lock This question has been locked and the reply function has been disabled.