javascript - 无法将 base64 字符串分配给类属性 - javascript

标签 javascript

我的目标是上传图像,我有一个方法,我想将base64字符串分配给类方法文件,问题是当我尝试获取属性中的值时,结果是未定义,我不明白为什么。我想将字符串分配给属性 _file 或在方法中返回它。

我的代码:

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
 <body>
    <form action="" enctype="multipart/form-data">
      <input type="file" />
      <input id="btn" type="submit" value="submit" />
    </form>
<script>
  class File {
    constructor() {
      this._file;
    }
    setFile(file) {
      const input = document.querySelector(file).files[0];
      const reader = new FileReader();
      reader.readAsDataURL(input);

      reader.onload = function () {
        this._file = reader.result.split(",")[1];
        console.log(this._file);
      };
    }
    getFile() {
      console.log(this._file);
    }
  }

  document
    .getElementById("btn")
    .addEventListener("click", function (event) {
      event.preventDefault();
      const file = new File();
      file.setFile("input[type=file]");
      file.getFile();
    });
</script>

最佳答案

你有两个微妙的错误:

reader.onload = function() {
    this._file = reader.result.split(",")[1];
    console.log(this._file);
};

这里,this关键字不是指向您的 File 实例,而是指向reader。这可以通过使用 arrow functions 来解决:

reader.onload = () => {
    this._file = reader.result.split(",")[1];
    console.log(this._file);
};

现在,this 关键字指向您的 File 实例。现在你有另一个问题:readAsDataURL是异步的,也就是说,它像AJAX一样在后台完成所有工作,而不会阻塞主线程。所以如果你有:

file.setFile("input[type=file]");
file.getFile();

无法保证 file.getFile() 会打印 _file 的更新值,因为您不知道读取器是否已完成其工作。所以我的建议是使用回调:

class File {
    constructor() {
        // ...
    }
    setFile(file, callback) {
        const input = document.querySelector(file).files[0];
        const reader = new FileReader();
        reader.onload = () => { // when reader has finished
            this._file = reader.result.split(",")[1]; // update _file property
            callback(); // execute callback
        };
        reader.readAsDataURL(input);
    }
    getFile() {
        console.log(this._file);
    }
}
document.getElementById("btn").addEventListener("click", function(event) {
    event.preventDefault();
    const file = new File();
    file.setFile("input[type=file]", function() {
        // put here all the code that uses the file variable
        file.getFile(); 
    });
});

现场演示

class File {
    constructor() {
        // ...
    }
    setFile(file, callback) {
        const input = document.querySelector(file).files[0];
        const reader = new FileReader();
        reader.onload = () => { // when reader has finished
            this._file = reader.result.split(",")[1]; // update _file property
            callback(); // execute callback
        };
        reader.readAsDataURL(input);
    }
    getFile() {
        console.log(this._file);
    }
}
document.getElementById("btn").addEventListener("click", function(event) {
    event.preventDefault();
    const file = new File();
    file.setFile("input[type=file]", function() {
        // put here all the code that uses the file variable
        file.getFile(); 
    });
});
<form action="" enctype="multipart/form-data">
  <input type="file" />
  <input id="btn" type="submit" value="submit" />
</form>

关于javascript - 无法将 base64 字符串分配给类属性 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61529078/

相关文章:

javascript - 将对象插入数组,操作会更改每个元素

javascript - javascript escape() 函数的正则表达式替代方案

javascript - D3 缩放行为阻止 IE9 中的点击事件

javascript - 如何使用 if else 语句显示单选按钮输入作为文本框中的输出

javascript - 如何在xmpp服务器中创建新组

javascript - 连续淡入淡出随机图片

javascript - Ember : Custom JSONAPISerializer

javascript - jquery 克隆组合框无法运行

php - onclick 增加计数器

javascript - 是否可以在 TypeScript 中创建 "weak export"