【问题标题】:angular2 filereader mysteriously failsangular2 文件阅读器神秘地失败了
【发布时间】:2023-03-30 17:33:01
【问题描述】:

我正在使用下面显示的设置来读取 angular2 中的图像文件。我正在使用input 元素来显示选择文件的窗口,然后在选择文件时触发addThumbnail 函数。点击input 是由另一个按钮触发的。我注意到addThumbnail 函数的触发有时会静默失败,即选择文件后甚至不会触发该函数。由于文件的大小,这种情况可能发生在 5 次中的 1 次。我不确定是否会发生这种情况。我试图通过在addThumbnail 函数中设置断点来调试它,但它甚至没有被触发。

<div class="extra-image-container">
    <input type="file" accept="image/*" (change)="addThumbnail($event)" style="display:none;" #fileInput2/>
    <div class="thumbnail-button" (click)="fileInput2.click()">
        <span><i class="material-icons">photo_camera</i></span><br>
        <span>Extra Images</span>
    </div>
</div>

这是我正在使用的 addThumbnail 函数和文件阅读器函数。

addThumbnail(event) {
    console.log('adding thumbnail');
    var subscription = this.readImage(event.target).subscribe((result) => {
        this.thumbnails.push(result.imageUrl);
        this.editedThumbnails.push(result.imageUrl);
        subscription.unsubscribe()
    });
}

readImage(inputValue: any) : Observable<any> {
    var file:File = inputValue.files[0]; 
    var myReader:FileReader = new FileReader();
    var observable = new Observable(observer => {
        myReader.onloadend = (e) => {
            observer.next({imageUrl: myReader.result});
            console.log("image loaded");
            // var image = new Image();
            // image.addEventListener("load", () => {
            //     observer.next({
            //         imageWidth: image.width,
            //         imageHeight: image.height,
            //         imageSize: file.size/1000,
            //         imageUrl: myReader.result
            //     })
            //     console.log("image loaded");
            // })
            // image.src = myReader.result;
        }
        myReader.readAsDataURL(file);//triggers the callback
    })
    return observable
}

【问题讨论】:

  • 看看日志会很好
  • 您的代码在 Chrome 60 上正常运行。顺便说一下,subscription.unsubscribe(); 似乎没用。
  • @LudovicGuillaume 这是反复试验的一部分,但感谢您指出。
  • @slesh 不确定如何生成日志,因为这些函数甚至都没有被调用
  • 你的测试环境怎么样? (ng 版本、cli 版本、浏览器...)

标签: html angular rxjs filereader


【解决方案1】:

事实证明,如果您一个接一个地读取相同的文件,则不会触发change,因为文件相同。所以,要解决这个问题,我所要做的就是在加载文件后将输入元素的值设置为空字符串。

@ViewChild('fileInput2') private thumbImageInput: ElementRef;
// and in the addThumbnail method: 
addThumbnail(event) {
    var subscription = this.readImage2(event.target).subscribe((result) => {
        this.thumbnails.push(result.imageUrl);
        this.editedThumbnails.push(result.imageUrl);
        window.URL.revokeObjectURL(result.imageUrl);
        this.thumbImageInput.nativeElement.value = '';
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    相关资源
    最近更新 更多