【问题标题】:Function is performed first than reading image data功能先于读取图像数据执行
【发布时间】:2019-11-20 04:54:22
【问题描述】:

我正在使用 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


    【解决方案1】:

    解释很简单。 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.
          };
    

    【讨论】:

    • 我认为是对的,但它不能正常工作:(
    • 我把函数放在 reader.onload = (e: any) => {它继续先执行。错误是上传函数先执行,而不是 image.onload = function () {因此接收宽度和高度未定义
    【解决方案2】:

    我想问题出在

     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
    }
    

    【讨论】:

    • 我认为是对的,但它不能正常工作:(
    • 那是因为需要先获取图片数据,然后调用上传函数。
    • 是的,就是这样,但我怎样才能正确地做到这一点?根据我的尝试,我没有成功获得结果:(
    • 一旦你得到图像数据示例: reader.onload = () => { // 你的图像数据;然后图像上传(); }
    猜你喜欢
    • 2022-06-11
    • 1970-01-01
    • 2014-05-03
    • 2022-07-06
    • 2017-08-16
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多