2017-08-17 70 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 = ''; 
    }); 
}