L. *_*ana 5 typescript primeng angular
我尝试从 prime-ng 库中读取使用以下组件上传的文件。
我的 html 组件:
<h3 class="first">Upload an excel file</h3>
<p-fileUpload name="myfiles[]"
chooseLabel="Choose a file"
uploadLabel="Show data
cancelLabel="Cancel"
accept=".csv"
maxFileSize="1000000"
auto="auto"
customUpload="true"
(uploadHandler)="myUploader($event)">
<ng-template pTemplate="toolbar">
<p-button label="Show data" icon="fa fa-upload" iconPos="left" (onClick)="myUploaderEnd($event)"></p-button>
</ng-template>
<ng-template pTemplate="content">
</ng-template>
</p-fileUpload>
<p *ngIf="datas.length > 1">{{datas[2].reference}}</p>
<p>{{debug}}</p>
Run Code Online (Sandbox Code Playgroud)
我的 TypeScript 组件:
import { Component, OnInit } from '@angular/core';
import {Message} from "primeng/api";
import {Data} from "../../shared/data";
import {DataService} from "../../services/data.service";
import {Routes, RouterModule, Router} from '@angular/router';
@Component({
selector: '....',
templateUrl: './file-upload-data.component.html',
styleUrls: ['./file-upload-data.component.css']
})
export class FileComponent implements OnInit {
dataService: DataService = new DataService();
uploadedFiles: any[] = [];
fileBuffer:string = "";
fileLines:string[] = [];
datas:Datas[] = new Array<Datas>();
debug: string = "";
file: File;
constructor(private router: Router) { }
ngOnInit() {
}
myUploader(event) {
for(let file of event.files) {
this.uploadedFiles.push(file);
}
}
myUploaderEnd(event) {
this.readFile(this.uploadedFiles[0]);
//this.datas= this.dataService.populateDatas(this.fileLines);
this.debug = this.uploadedFiles[0].name+"----"+this.fileBuffer;
}
readFile(file: File) {
var reader = new FileReader();
reader.onload = () => {
this.fileBuffer+=reader.result;
};
reader.readAsText(file);
this.fileLines = this.fileBuffer.split("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
第一次单击调用函数 myUploaderEnd 的按钮时,我没有任何数据,fileBuffer 的值为 null。我第二次单击同一个按钮时,变量中有值......
我想在第一次单击时从文件中读取数据,但我没有解释为什么需要两次单击。
谢谢。
在调试期间 reader.onload 事件是代码的最后一部分,称为...
export class FileComponent {
uploadedFiles: any[] = [];
fileBuffer:string = "";
fileLines:string[] = [];
debug: string = "";
file: File;
reader: FileReader;
constructor(private router: Router,private importService: ImportService ) {
this.importService.setActiveIndex(0);
this.reader = new FileReader();
this.reader.onload = () => {
this.fileBuffer=this.reader.result;
this.fileLines = this.fileBuffer.split("\n");
this.debug += ""+this.uploadedFiles[0].name+"----"+this.fileBuffer+"!!!!!!";
this.importService.setActiveIndex(1);
this.router.navigate(["/app/import/consulter"]);
};
}
myUploader(event) {
for(let file of event.files) {
this.uploadedFiles.push(file);
}
}
myUploaderEnd(event) {
this.readFile(this.uploadedFiles[0]);
}
readFile(file: File) {
this.reader.readAsText(file);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16226 次 |
| 最近记录: |