1
我正在執行文件上載並處於更改事件中我正在使用FileReader讀取文件並將字符串分配給變量。但在提交方法中,變量顯示爲未定義。分配給局部變量的值在角度4中得到了未定義
我的代碼
HTML:
<form #yourForm="ngForm" (ngSubmit)="addDocument()">
<div class="col-md-12">
<div class="form-group form-black">
<label class="control-label">Select file: </label>
<input type="text" [(ngModel)]="Name" name="Name" class="form-group" />
<input type="file" #fileupload [(ngModel)]="myFile" name="myFile" (change)="fileChange(fileupload.files)" />
</div>
</div>
<div class="col-md-12">
<div class="form-group form-black pull-right">
<button type="submit">Submit</button>
</div>
</div>
</form>
component.ts
document: IDocuments = {docstream:''};
Name: string;
myFile: File; /* property of File type */
upFile: File;
fileStream: string;
fileChange(files: any) {
this.upFile = files[0];
this.Name = this.upFile.name;
this.getBase64(this.upFile, function (e) {
let result = e.target.result;
this.fileStream=result.split(',')[1];
console.log("In: "+this.fileStream);
})
console.log("Out: "+this.fileStream);
this.document.docstream = this.fileStream;
}
getBase64(file, onLoadCallback): string {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = onLoadCallback;
return reader.result;
}
addDocument(): void {
console.log("addDocument: "+this.fileStream);
console.log(this.document.docstream);
this._fileuploaderService.uploadDocument(this.document)
.subscribe(s => { });
}
console.log("In: "+this.fileStream); //is showing the result
但
console.log("Out: "+this.fileStream); //is showing undefined
console.log("addDocument: "+this.fileStream); //is showing undefined
會有什麼問題?在更改事件之後,this.fileStream應該顯示一些結果,不是嗎?
非常感謝你...你節省了我的時間:) –