我在Angular 9中开发了一个项目,该项目读取csv文件并将其内容发送到服务器。 我有一个用于文件记录的模型。
该请求在“请求有效负载”中显示该对象,但是当它到达API控制器时,数据不会被识别为[FromBody]参数。
您对我有什么解决办法吗? 这是我的代码:
型号:
export class CSVRecord {
public code: string;
public date: Date;
public value: number;
public period: string;
}
类型脚本:
export class AppComponent {
title = 'FastWayToSerieses-Client';
constructor(public apiService: ApiService, private http: HttpClient ) {
}
public records: any[] = [];
@ViewChild('csvReader') csvReader: any;
uploadListener($event: any): void {
const text = [];
const files = $event.srcElement.files;
if (this.isValidCSVFile(files[0])) {
const input = $event.target;
const reader = new FileReader();
reader.readAsText(input.files[0]);
console.log('after read as text');
reader.onload = (e) => {
console.log('onload');
const csvData = reader.result;
const temp = ( csvData as string).replace(/\r/g, '\n');
const csvRecordsArray = ( temp as string).split(/\r\n|\n/);
const headersRow = this.getHeaderArray(csvRecordsArray);
this.records = this.getDataRecordsArrayFromCSVFile(csvRecordsArray, headersRow.length);
(document.getElementById('sendButton') as HTMLInputElement).disabled = false;
};
} else {
alert('Please import valid .csv file.');
this.fileReset();
}
}
getDataRecordsArrayFromCSVFile(csvRecordsArray: any, headerLength: any) {
console.log('getDataRecordsArrayFromCSVFile');
const csvArr = [];
for (let i = 1; i < csvRecordsArray.length; i++) {
const curruntRecord = (csvRecordsArray[i] as string).split(',');
if (curruntRecord.length === headerLength) {
const csvRecord: CSVRecord = new CSVRecord();
csvRecord.code = curruntRecord[0].trim();
csvRecord.date = new Date(curruntRecord[1].trim());
csvRecord.value = Number(curruntRecord[2].trim());
csvRecord.period = curruntRecord[3].trim();
csvArr.push(csvRecord);
}
}
return csvArr;
}
isValidCSVFile(file: any) {
return file.name.endsWith('.csv');
}
getHeaderArray(csvRecordsArr: any) {
console.log('getHeaderArray');
const headers = (csvRecordsArr[0] as string).split(',');
const headerArray = [];
for (const header of headers){
headerArray.push(header);
}
return headerArray;
}
fileReset() {
this.csvReader.nativeElement.value = '';
this.records = [];
}
这是将数据确定到服务器的功能:
sendCSV(){
console.log('click');
const url = this.apiService.baseUrl + 'API/SeriesAPI/UploadSeriesData?option=1';
// const body = JSON.stringify(this.records);
this.http.post(url, this.records ,
{
headers: new HttpHeaders({
'Content-Type': 'application/json;chrset=UTF-8'
})
}
)
.subscribe(x =>
{
console.log(x);
});
}