2016-11-28 118 views
3

我正嘗試在Angular 2 ts(2.2.1)中創建一個上傳表單,該表單允許上載例如一個CSV文件,而不是直接發送到http服務的文件,我希望首先在瀏覽器中驗證文件。在Angular 2中從FileReader獲取數據

到目前爲止,我已經可以上傳文件,並使用此代碼打印在控制檯:

  1. 文件的HTML輸入上傳

    <input type="file" (change)="changeListener($event)" #input /> 
    
  2. 在我的角度分量我已經設置了eventListner和文件讀取器。

    export class UploadComponent { 
    
        public fileString; 
    
        constructor() { 
         this.fileString; 
        } 
    
        changeListener($event): void { 
          this.readThis($event.target); 
         } 
    
        readThis(inputValue: any): void { 
         var file: File = inputValue.files[0]; 
         var myReader: FileReader = new FileReader(); 
         var fileType = inputValue.parentElement.id; 
         myReader.onloadend = function (e) { 
          //myReader.result is a String of the uploaded file 
          console.log(myReader.result); 
    
          //fileString = myReader.result would not work, 
          //because it is not in the scope of the callback 
         } 
    
         myReader.readAsText(file); 
        } 
    } 
    

此代碼工作完全正常爲止。

但是,我還沒有找到一種方法來存儲來自閱讀器的數據,使我可以用我的角度組件訪問它。

myReader.onloadend()回調函數無法訪問組件的變量。有沒有辦法注入這些變量?

如何將讀取的數據讀入組件中的fileString變量?

回答