首先执行功能是读取图像数据

问题描述 投票:0回答:2

我正在使用angular,并且具有执行图像输入的功能。

通过插入的图像,我删除了它们的信息,例如名称,大小...我的问题是,在上传图像时(我将需要知道图像的高度和宽度),首先执行上传功能,而不是从该图像中获取信息的功能。

作为问题,我在宽度和高度上都不确定。

上传功能首先执行image.onload:(

有人知道为什么吗?

Component.ts

  detectFiles(event) {

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

        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]);
      }
    }
  }
angular typescript
2个回答
0
投票

解释很容易。 Javascript是一种顺序语言,但是在您的方案中,您不能确定哪个命令位于堆栈的前面。

下面的代码只是说,当某些事件调用onload函数时,执行它。

      image.onload = function () {
        item.sizeH = image.width;
        item.sizeV = image.height;
        self.sizeH = item.sizeH;
        self.sizeV = item.sizeV;
      };

然后,在任何人调用该函数之前,您都可以继续进行操作并使用订阅上载。通常先执行顺序命令。

如果您在onload函数中进行了上传,则不会有问题。

      image.onload = function () {
        item.sizeH = image.width;
        item.sizeV = image.height;
        self.sizeH = item.sizeH;
        self.sizeV = item.sizeV;
        // upload logic here.
      };

0
投票

我想问题出在

 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;
        item.sizeV = image.height;
        self.sizeH = item.sizeH;
        self.sizeV = item.sizeV;
      };

如果有帮助,请尝试使用这种方式

reader.onload = () => {
 // Your code to be implemented
}
© www.soinside.com 2019 - 2024. All rights reserved.