【问题标题】:Capture result of HTML5 FileReader to a variable using promises使用 Promise 将 HTML5 FileReader 的结果捕获到变量中
【发布时间】:2018-11-15 12:24:32
【问题描述】:

我有一个 Angular 4 应用程序,我正在读取图像并尝试将 base64 字符串传递给另一个变量 - 但是由于它的异步性质,我遇到了问题 - image.src 是空的,因此值是否已正确传递给图像对象?

ngAfterViewInit(): void {
    let image = new Image();
    var promise = this.getBase64(fileObject, this.processImage());
    promise.then(function(base64) {
        console.log(base64);    // outputs string e.g 'data:image/jpeg;base64,........'
    });

    image.src = base64; // how to get base64 string into image.src var here??          
}

/**
 * get base64 string from supplied file object
 */
public getBase64(file, onLoadCallback) {
    return new Promise(function(resolve, reject) {
        var reader = new FileReader();
        reader.onload = function() { resolve(reader.result); };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

public processImage() {

}

【问题讨论】:

    标签: javascript asynchronous promise base64 filereader


    【解决方案1】:

    您遇到的问题是base64 是变量,作用于.then() 的回调函数。要使其正确,只需执行以下操作:

    ngAfterViewInit(): void {
        let image = new Image();
        var promise = this.getBase64(fileObject, this.processImage());
        promise.then(function(base64) {    // base64 variable is scoped to this function only.
            console.log(base64);    // outputs string e.g 'data:image/jpeg;base64,........'
    
            image.src = base64;
        });
    }
    

    【讨论】:

    • 我需要向 processImage() 添加任何内容吗?目前我在代码中的image.src = base64 行上得到一个'type {} 不可分配给字符串?承诺把我搞糊涂了:)
    • 使用promise时为什么要使用回调?
    猜你喜欢
    • 2019-04-12
    • 2017-09-08
    • 2018-04-22
    • 1970-01-01
    • 2023-03-22
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多