2017-08-17 34 views
0

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

<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 
} 
+0

这将是很好看 – slesh

+0

你的代码是正确的在Chrome 60工作顺便说一句,'subscription.unsubscribe(日志);'好像没用。 –

+0

@LudovicGuillaume是试验和错误的一部分,但谢谢指出。 – quantdaddy

回答

0

事实证明,如果你接连读取相同的文件之一,则change没有被触发,因为这些文件是相同的。所以,为了解决这个问题,我只需要在加载文件后将input元素的值设置为空字符串。

@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 = ''; 
    }); 
}