首页 > 解决方案 > 上传功能前执行 Image.onload

问题描述

我正在使用角度,并且我有一个执行图像输入的函数。

通过插入的图像,我删除了它们的名称,大小等信息......我的问题是上传图像时(我需要知道它的高度和宽度),上传功能比我从中获取信息的功能先执行那个图像。

作为一个问题,我得到一个未定义的宽度和高度。

上传功能先于 image.onload :(

有谁知道为什么?

组件.ts

  detectFiles(event) {       
    var files = event.target.files;
    if (files.length < 8) {
      for (let index = 0; index < files.length; index++) {

        const item: any = {
          filename: event.target.files[index].name.split('.')[0],
        };

        this.filename = item.filename;
        this.items.push(item);
        const reader = new FileReader();
        reader.onload = (e: any) => {
          item.url = e.target.result;
          const image = new Image();
          image.src = e.target.result;
          image.onload = function () {
            item.sizeH = image.width;

          };

        }
        formData.append('file', files[index]);
        reader.readAsDataURL(files[index]);
      }

    }
  }

标签: angulartypescript

解决方案


发生这种情况是因为 onload 是异步的,并且在onload()仍在运行时,脚本会继续执行并到达upload.

您可以通过将上传代码移动到它自己的函数中来重构代码,然后从内部调用它,onload()如下所示:

detectFiles(event) {
...
if (files.length < 8) {
    ...
    reader.onload = (e: any) => {
      ...
      image.onload = function() {
         ...
         uploadFile(formData, stamp, encrPath, sizeH, sizeV); // < Call the upload here
      };
    };
    ...
    }
}

uploadFile(formData, stamp, encrPath, sizeH, sizeV) {
  this.Global.refreshToken().subscribe(function(result) {
    self.uploadService
      .postImage(formData, stamp, encrPath, sizeH, sizeV)
    ...
  });
}

推荐阅读